[rspec-users] When to use Factories, Mock Models, Mocks & Stubs

Adam Sroka adam.sroka at gmail.com
Wed Feb 3 01:06:05 EST 2010

On Tue, Feb 2, 2010 at 9:53 PM, Andrei Erdoss <erdoss at gmail.com> wrote:
> Hello Frank,
> From my understanding these are the roles of should_receive and stub.
> should_receive checks to make sure that a method or a property is called. To
> this you can specify the arguments that it gets called (.with()), what it
> returns (.and_return) and how many times this happens (.once, .twice etc).
> stub on the other hand is a place holder for functions calls that have been
> tested already or are Rails defaults, which don't need to be tested. stubs
> are used in conjunction with mock_models, in order to provide for the
> functions or properties that are needed for the code to run, up to the test
> point.

I think that it is best to think of these in terms of command query
separation. In case you aren't familiar with that principle, it states
that some methods are commands - they tell an object to do something
but don't return anything interesting, and other methods are queries -
they return some interesting value but have no side effects.

should_receive is how we set an expectation for a command. We don't
really care what a command returns but we do care that it gets called.
should_receive literally says that the command should be called with
the given parameters.

stub is how we handle a query. We care what a query returns, or rather
the code we are testing does, but we don't really care when it gets
called (or how often) per se. If we depend on its result then it
should be called, but the effect that the result has on the system
we're testing is what we really care about.

More information about the rspec-users mailing list