Skip to content

Instantly share code, notes, and snippets.

@ianyamey
Last active March 24, 2016 11:28
Show Gist options
  • Select an option

  • Save ianyamey/e43dd1f5a8601fe61b52 to your computer and use it in GitHub Desktop.

Select an option

Save ianyamey/e43dd1f5a8601fe61b52 to your computer and use it in GitHub Desktop.
A spec helper for VCR that separates cassettes into directories

The "vcr.rb" spec helper in this gist will create cassettes with readable filename structures. It aims to avoid extremely long filenames for cassets that can break Docker builds.

For example:

# spec/features/life/quotes_widget_spec.rb
describe 'Life quotes widget', :vcr do
  context 'when the user knows their coverage amount' do
    it 'redirects to the health navigator' do
      # ...
    end
  end
  context 'when the user does not know their coverage amount' do
    it 'redirects to the coverage navigator' do
      # ...
    end
    it 'saves the foo and the bar' do
      # ...
    end
  end
end

Will generate cassettes:

spec/
  cassettes/
    life_quotes_widget/
      when_the_user_knows_their_coverage_amount/
        redirects_to_the_health_navigator.yml
      when_the_user_does_not_know_their_coverage_amount/
        redirects_to_the_coverage_navigator.yml
        saves_the_foo_and_the_bar.yml
# ./spec/support/vcr.rb
require 'rails_helper'
require 'vcr'
require 'webmock'
VCR.configure do |config|
config.ignore_localhost = true
config.cassette_library_dir = 'spec/cassettes'
config.hook_into :webmock
end
RSpec.configure do |config|
config.around(:each, :vcr) do |example|
cassette_name = example.metadata[:description]
shelf_names = example_group_names(example.metadata[:example_group])
cassette_filename = (shelf_names + [cassette_name])
.map { |n| n.parameterize('_') }
.join('/')
options = example.metadata.slice(:record, :match_requests_on)
VCR.use_cassette(cassette_filename, options) { example.call }
end
config.before(:each) do
$vcr_cassette_log = []
end
end
# Returns: A flat array of names of the example group heirarchy
def example_group_names(example)
return if example.nil?
names = []
names << example_group_names(example[:parent_example_group])
names << example[:description]
names.compact.flatten
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment