Usage Modes: Mocks, Stubs, and Spies

First, let’s talk about the different usage modes of test doubles.

Generic Test Doubles

RSpec’s double method creates a generic test double that you can use in any mode. The simplest way to call this method is with no arguments. Let’s try that now:

 >>​ ledger = double
 => #<Double (anonymous)>

In some ways, this double acts like an ordinary Ruby object. As you send messages to it (in other words, call methods on it), it will accept some messages and reject others.

The difference is that a generic double gives you more debugging information than a regular Ruby object. Try sending the record message to your test double now:

 >>​ ledger.record(​an: :expense​)
 RSpec::Mocks::MockExpectationError: #<Double ...

Get Effective Testing with RSpec 3 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.