Small helper to conditionally re-record VCR cassettes

Posted . Visible to the public.

I find it annoying to iterate on a spec that relies on a recorded VCR casette Show archive.org snapshot . You constantly have to remove the same YAMLs file before you can re-run that still-red test.

With this little helper, you (or your coding agent) can do the same with RE_RECORD_VCR=true bundle exec rspec spec/path/to/recorded_spec.rb:

# spec/support/vcr.rb

RSpec.configure do |config|
  deleted_vcr_cassettes = []

  config.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)

    if %w[true 1].include?(ENV['RE_RECORD_VCR'])
      unless deleted_vcr_cassettes.include?(name)
        cassette_path = File.join(VCR.configuration.cassette_library_dir, "#{name}.yml")
        FileUtils.rm_f(cassette_path)
        deleted_vcr_cassettes << name
      end

      options[:record] = :new_episodes
    end

    VCR.use_cassette(name, options) { example.call }
  end
end

See also

Profile picture of Michael Leimstädtner
Michael Leimstädtner
Last edit
Michael Leimstädtner
License
Source code in this card is licensed under the MIT License.
Posted by Michael Leimstädtner to makandra dev (2026-04-13 09:48)