I'm currently in the process of writing unit tests for a small website running Ruby on Sinatra. We're using MiniTest for our unit tests and are starting to run into some issues with maintaining test integrity with our data.
We currently run a test database that is cleared and reset between each 'set' of tests. As our tests grow, this process is beginning to take much longer than we anticipated. In addition, there's concern that we should be keeping each individual test separate instead of using the same database instance for each set.
I've started looking into mocks, but I'm not sure if I'm going down the right path here. I'm having trouble on finding much documentation on this.
Currently, we have something like this:
To be tested:
def run(user_id)
if user_id < 100
return User.get_by_id(user_id)
end
false
end
The test:
describe 'run' do
before do
reset_environment
end
it 'should return false if the user_id is >= 100' do
run(100).must_equal false
end
it 'should return User object if user_id is < 100' do
run(99).must_be_instance_of User
end
end
As I said, the tests were starting to take forever to run, and it seemed incredible inefficient. So I'm trying to rewrite things by mocking out the user (in this simplified example). Is this correct?
To be tested:
def run(user_id, User: User)
if user_id < 100
return User.get_by_id(user_id)
end
false
end
The test:
describe 'run' do
user_mock = MiniTest::Mock.new
user_mock.expect(:get_by_id, true, [Integer])
subject (:run_with_mock) { |user_id| run(user_id, user_mock) }
it 'should return false if the user_id is >= 100' do
run_with_mock(100).must_equal false
end
it 'should return User object if the user_id is < 100' do
run_with_mock(99).must_equal true
end
end
Is this the correct way to be going about things, or am I completely off base? It seems to work, but it seems incredibly counter-intuitive.
Aucun commentaire:
Enregistrer un commentaire