I’m using rspec and the rspec mocks library for stubbing/mocking, but I’m starting to think that the line between stubbing out a method and asserting how it’s been used is blurred. In my tests I’ll often write something like:
before(:each) do
subject.should_receive(:sum).once.with([1, 2, 3]).and_return(6)
end
it("should do something that relies on sum") do
subject.call_something([1, 2, 3]).should == 24
end
But what are my assertions? That call_something([1, 2, 3]):
- Returns
24 - Calls
sum([1, 2, 3])during it’s execution
However, there is only one it block – the other assertion is hidden away in the stub definition. To put it another way, my stub is also my assertion. Wouldn’t it be much clearer to separate the two, and put an explicit assertion in for how the stubbed method was called:
before(:each) do
# set up what my stub should return for a given input
subject.may_receive(:sum).with([1, 2, 3]).and_return(6)
end
# assert how my stub was actually called
it("should have called sum with 1, 2, 3") do
# this is pseudo-rspec
subject.call_something([1, 2, 3]).should have_called(:sum).on(subject).once.with([1, 2, 3])
end
it("should do something that relies on sum") do
subject.call_something([1, 2, 3]).should == 24
end
This way it’s very clear what I’m asserting because my stub definitions and assertions have been separated. I can setup my test at the top, and then check it’s behaviour at the bottom, without mixing the two.
So, my question is whether there’s a way of doing this? Most mocking frameworks work in the same way as rspec-mocks, and define the contract for how a stub method is used along with the expected behaviour, and then automagically check the assertion at the end.
My point is a conceptual one about how BDD works, and might be a bit subtle. Let me know I need to clarify it further!
You’re correct.
should_receiveis an assertion (more accurately it is an expectation) and should not go in abeforeblock. If you need the stubbing side-effect ofshould_receive, then stub separately in yourbefore:This keeps the stubbing and expectation separate and where they belong.