[rspec-users] Surprising mock behavior

Stephen Eley sfeley at gmail.com
Fri Oct 17 15:37:01 EDT 2008

On Fri, Oct 17, 2008 at 2:55 PM, Mark Thomson <mark.thomson at ieee.org> wrote:
> and then check that the expected messages are being received -
> file.should_receive(:puts).with("a string").once
> file.should_receive(:puts).with("another string").once
> Here's what I'm puzzled about. If I don't include the expectation for the
> first string in the spec, the spec will fail the expectation for the second
> string. It seems as if "should_receive" is queuing up the messages that come
> into the file object and when it tests an expectation it just looks at the
> next one in line. If it doesn't match then the expectation will fail.

That sounds right to me.  You declared 'file' as a mock.  Mocks are
bratty little children that treat it as an error and throw a tantrum
if you don't give them everything they expect, no more nor less.  (As
contrasted to stubs, which are couch potatoes that will respond if you
call them but don't complain if you don't.)

So when you create a mock, you need to be very thorough about it.
Every message has to be accounted for somehow.  If it gets more
messages than you tell it, or different messages, it'll error.  If it
doesn't get enough messages, it'll error.  This is correct behavior.

If the exact parameters aren't part of your test plan, you could
always say file.should_receive(:puts).twice and leave off the
parameter expectation.  Or just file.should_receive(:puts) if you know
it should happen but don't care how often, or
file.should_receive(:puts).any_number_of_times if it could be zero as

Or, if that all sounds like too much work, make 'file' a stub object
instead of a mock object and stub the :puts method:

file = stub('file', :puts => true)

...and then only set should_receive for the things you care about in
specific tests.

Does that help, or is the behavior still anomalous even knowing that
mocks are super-finicky?

Have Fun,
   Steve Eley (sfeley at gmail.com)
   ESCAPE POD - The Science Fiction Podcast Magazine

More information about the rspec-users mailing list