Simple stubs with RSpec

Ruby on Rails / Testing

Mostly, writing a spec you would like to stub classes used in a class that you are testing. We don’t want to hit the database if it’s not needed. In order to do this, you have to use stubs. Stubs are instructions that allow to call given method and return desired value without calling code inside the method.

There are three base steps to do this:

  1. Allow given class or class instance
  2. To receive given method
  3. And return desired results

If you have Post model and #title method you can use following code to stub model instance:

allow(post).to receive(:title).and_return('title')

If your method takes one or more arguments there is one extra step: with part.

allow(post).to receive(:title).with(argument_1, argument_2).and_return('title')

The goal is to control how exactly we call given method.

If you want to stub any instance of a given object you can use this code:

allow_any_instance_of(Post).to receive(:title).and_return('title')

Using this code forces any instance of Post model to return title when calling #title method