A stub is a replacement for all or part of an object that prevents a normal method call from happening and instead returns a value that is preset when the stub is created.

In RSpec, there are two kinds of stubs:

  • We can create entire objects that exist only to be stubs, which we’ll call full doubles.
  • We can stub specific methods of existing objects, which we’ll call partial doubles.

Partial doubles vs. full doubles

A partial double is useful, for example, when we want to use a “real” ActiveRecord object but we have one or two dangerous or expensive methods we want to bypass.

A full double is useful when we’re testing that the code works with a specific API rather than a specific object. Bypassing in a generic object that responds to only certain methods, we make it hard for the code to assume anything about the structure of the objects being used by the code under test.

Note: Use partial doubles when we want to ensure most of the real object behavior. Use full doubles when the behavior of the stubbed object doesn’t matter and only its public interface does.

Full doubles

In RSpec, we create full doubles with the double method, which is available anywhere. The double method takes an optional string argument, which is a name for the double, and then key-value pairs representing messages that can be sent to the double. Since Ruby uses duck typing, which is to say it does not care about the type of objects but only about whether objects respond to the messages sent to them, a stub object created in such a way can be inserted into the application as a replacement for a real object:

Get hands-on with 1200+ tech skills courses.