Spec::Mocks
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_and_options)
As above, but allows you to set stub return values for specific messages and
options that tweak the mock’s behaviour. Currently the only supported option
is :null_object. Setting this to true instructs the mock to
ignore (quietly consume) any messages it hasn’t been told to expect – and
return itself.
my_mock = mock("blah", :null_object => true)
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:
- Mock Objects: http://www.mockobjects.com/
- Endo-Testing:http://www.mockobjects.com/files/endotesting.pdf
- Mock Roles, Not Objects: http://www.mockobjects.com/files/mockrolesnotobjects.pdf
- Test Double Patterns: http://xunitpatterns.com/Test%20Double%20Patterns.html
- Mocks aren’t stubs: http://www.martinfowler.com/articles/mocksArentStubs.html
