RSpec: automatic creation of VCR cassettes

Updated . Posted . Visible to the public. Repeats.

You can configure VCR to automatically record/replay cassettes for any RSpec example tagged as :vcr or vcr: true.

  • If a spec is not tagged with :vcr, VCR will complain about any attempted HTTP request. This is the default behaviour. If you want to turn this off temporarily, e.g. to communicate with an actual API while writing a new spec, simply add the line c.allow_http_connections_when_no_cassette = true to the VCR.configure-block.

  • If a spec is tagged with :vcr, a cassette with an automatically determined name will be generated on the first test run and replayed on subsequent runs:

Here is an example for a spec using the :vcr tag:

# spec/models/<model_name>/<file_name>_spec.rb
describe ModelName::ExampleApi do

  describe '<group>' do
    it '<example>', :vcr do
      # calls to API
      # expectations
    end
  end
  
end

Built-in hook

VCR can define the hook for you by configuring:

VCR.configure do |c|
  c.configure_rspec_metadata!
end

This saves cassettes here:

spec/cassettes/
  <group>/
    <example>.yml

Custom hook

If you need more control, you can define the vcr: true hook yourself:

# spec/support/vcr.rb
VCR.configure do |c|
  c.cassette_library_dir = Rails.root.join("spec", "vcr")
  c.hook_into :webmock
end

RSpec.configure do |c|
  c.around(:each, :vcr) do |example|
    name = example.metadata[:full_description].split(/\s+/, 2).join("/").underscore.gsub(/[^\w\/]+/, "_")
    options = example.metadata.slice(:record, :match_requests_on).except(:example_group)
    VCR.use_cassette(name, options) { example.call }
  end
end

This saves cassettes here:

spec/vcr/
  <model_name>/
    <file_name>_<describe_title>/
      <it_title>.yml

Behaviour

Profile picture of Klaus Weidinger
Klaus Weidinger
Last edit
Henning Koch
License
Source code in this card is licensed under the MIT License.
Posted by Klaus Weidinger to makandra dev (2021-10-11 11:50)