Read more

Verifying doubles in RSpec 3

Henning Koch
April 02, 2015Software engineer at makandra GmbH

RSpec 3 has verifying doubles Show archive.org snapshot . This breed of mock objects check that any methods being stubbed are present on an instance of a given class. They also check methods aren't called with the wrong number of arguments.

This dual approach allows you to move very quickly and test components in isolation, while
giving you confidence that your doubles are not a complete fiction.

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

You should always prefer using a verifying double to using an old-school mock or double instance.

Using verifying doubles

Like this:

class User
  def login
    ...
  end
end

user = instance_double(User) # instead of double(User, login: 'u123')
expect(user).to receive(:login).and_return('u123') # works
expect(user).to receive(:screen_name).and_return('u123') # raises "User does not implement: screen_name"

I strongly recommend to instantiate the instance_double using the class objects (User) instead of the class name string ("User") as you see in the examples. If you use a non-existing class name, verifying doubles fail silently.

There is also an option verify_doubled_constant_names which you can set in your spec_helper.rb, but this one requires you to eager-load your entire model tree before running specs.

Verifying partial doubles

See Configure RSpec to raise an error when stubbing a non-existing method.

Verifying dynamically defined methods

You might run into trouble with using this approach, when you are stubbing dynamically defined methods with an error like <view> does not implement: current_power.
The documentation on dynamic classes Show archive.org snapshot includes some ways to fix this by showing how dynamically defined attribute methods from ActiveRecord are verified. Note that this is enabled by default when you are using rspec-rails along with verifying doubles.

So if you really need to verify some dynamically defined methods you can follow the approach of the documentation. However for most use cases it will be the easiest to simply disable verifying doubles for the affected specs.

Verifying doubles in RSpec 2

For older RSpecs there is rspec-fire Show archive.org snapshot .

Posted by Henning Koch to makandra dev (2015-04-02 12:30)