Q: Where should I place the mocks in my test?
astyagun opened this issue · comments
describe '#method1' do
before { expect(SomeClass).to receive(:method2) }
subject { described_class.new.method1 }
it 'calls SomeClass.method2' do
subject
end
end
VS
describe '#method1' do
subject { described_class.new.method1 }
it 'calls SomeClass.method2' do
expect(SomeClass).to receive(:method2)
subject
end
end
I think the second one is correct since you wanted to test, that the method is called so the expect
should be in the it
block. If this fails the it
will fail and all other it
s can pass.
A even better way could be (in my opinion)
describe '#method1' do
subject { described_class.new.method1 }
before {allow(SomeClass).to receive(:method2)}
it 'calls SomeClass.method2' do
subject
expect(SomeClass).to have_received(:method2)
end
end
The benefit would be, that you can have several it
s and only the the method call it tested in one case.
Thanks @geniou, we've had an argument about this at work and your solution satisfies both sides :)
@astyagun your welcome. :)
@astyagun if your issue has been resolved, please close it. Otherwise, I am leaving it open.
In the future, I plan to have a forum or chat for questions like this, as they can be solved soon. (Like this one was.) When we overhaul the site, issues will be general questions on best practice or about the code.... not personal cases of "what's best to do"