Mocks and Stubs

Mock objects are imitation objects that give you declarative control over their
behaviour in the course of the execution of an example. Defining message
expectations
and method stubs on mock
objects allows you to specify how one object collaborates with others before
those other objects exist.

You can also use mock objects to isolate your examples from services that are
complex to set up or expensive to run, thereby keeping your suite of examples
running quickly.

RSpec ships with a built-in mock object framework that lets you create mock
objects in your examples or add mock-object-like behaviour to your existing
objects.

Creating a mock object

You create a mock object with the mock method:

my_mock = mock(name)

This creates a new mock with the given name (a string) and
registers it. When the example finishes, all registered mocks are verified.

my_mock = mock(name, stubs)

As above, but allows you to set stub return values for specific messages.

Notes

There are many different viewpoints about the meaning of mocks and stubs. If
you are interested in learning more, here is some recommended reading: