Ivan Tkalin

I’m a software engineer. I solve problems.

Upgrading to RSpec 3.x

This short article is TL;DR of the talk: RSpec 3 and why I expect(you).to care by Jon Rowe. I picked 3 important recommendations out of this talk which I’m going to follow.

1. Use zero monkey patching mode

This will completely disable all the monkey patching and will make RSpec less magical. Of course, it has a few consequences:

  • DSL will not be exposed globally, so RSpec.describe must be used instead of describe etc.
  • should and should_not syntax will be disabled, so expect() syntax must be used.

To enable zero monkey patching mode, just add this line to RSpec configuration:

  config.disable_monkey_pathing!

2. Use verified doubles

This will enable checking that the contract of the mock corresponds to the contract of the real object. It means that if methods being mocked/stubbed are not actually implemented by the object behind test double, the test will fail with error.

Once it’s enabled, instance_double should be used instead of double to create verified doubles. allow() and expect() methods for real objects just work.

To enable verified doubles, just add this line to RSpec configuration:

  config.verify_partial_doubles = true

Note: this doesn’t play very well with ActiveRecord::Base models in Rails, because Rails loads columns dynamically, so don’t try to verify columns of rails models.

3. Upgrading from RSpec 2 to 3:

Upgrade from RSpec 2 to RSpec 3 should be easy if you follow this simple guide:

  1. Upgrade to latest version of RSpec 2.99 first and fix all deprecations
  2. Use transpec to convert all existing specs to 3 syntax