Setting up VCR and webmock for Cucumber testing


In order to setup VCR and webmock for cucumber testing you should:

Add webmock and VCR gems to your Gemfile.rb:

group :test do
  gem 'webmock'
  gem 'vcr'

Add file called vcr_setup.rb in your /features/support/ folder that will be used for VCR configuration.

# features/support/vcr_setup.rb
require 'vcr'
VCR.configure do |c|
  c.cassette_library_dir = 'features/cassettes'
  c.hook_into :webmock
  c.ignore_localhost = true
VCR.cucumber_tags do |t|
  t.tag [email protected]', :use_scenario_name => true

Add require ‘webmock/cucumber’ to /features/support/env.rb.

# features/support/env.rb
require 'webmock/cucumber'
Now run your tests!

Your tests are now behaving like they are in a bubble: totally independent from their environment. If some of them were working, but now they are failing, that is because they are trying to make an API call.
To fix them just add @vcr to the top of the tests. Now the API call will be allowed, and it will be recorded saved in features/cassettes and later reused whenever there is an API call from that test.

Happy testing!