Automatically record all remote calls (with RSpec) - vcr/vcr GitHub Wiki

To "magically" add VCR to all your remote calls, you can add the following code to your spec configuration:

RSpec.configure do |config|
  # Add VCR to all tests
  config.around(:each) do |example|
    vcr_tag = example.metadata[:vcr]

    if vcr_tag == false
      VCR.turned_off(&example)
    else
      options = vcr_tag.is_a?(Hash) ? vcr_tag : {}
      path_data = [example.metadata[:description]]
      parent = example.example_group
      while parent != RSpec::ExampleGroups
        path_data << parent.metadata[:description]
        # Newer versions of rspec may require you to use module_parent instead
        # parent = parent.module_parent
        parent = parent.parent
      end

      name = path_data.map{|str| str.underscore.delete('.').gsub(/[^[:word:]\-\/]+/, '_').chomp('/')}.reverse.join("/")

      VCR.use_cassette(name, options, &example)
    end
  end
end 

This approach only VCR creates cassettes to the tests with remote calls and you won't have to manually create cassettes but this approach has the following drawbacks:

  • This adds some extra processing (i.e. inserting the cassette before, and ejecting the cassette after) to each and every example. I don't think it's super slow, but it does add up.
  • This is very implicit.
  • This uses a different cassette for each and every example (since it's based on the example description). Many (most?) times you can use one cassette for multiple examples, which saves hard drive space and keeps your git repository from growing unnecessarily large (which affects, among other things, the time it takes to clone it, and thus may affect your deploy times).