Skip to content

Instantly share code, notes, and snippets.

@dideler
Last active January 6, 2024 15:13
Show Gist options
  • Save dideler/062a6d6722e137db55b2 to your computer and use it in GitHub Desktop.
Save dideler/062a6d6722e137db55b2 to your computer and use it in GitHub Desktop.
Show unused VCR cassettes. Use with vcr gem: https://github.com/vcr/vcr
# Require this file in spec_helper.rb to show which cassettes are not being used
# after the test suite has run. Then you can decide if you want to delete them.
require 'vcr'
require 'set'
USED_CASSETTES = Set.new
module CassetteReporter
def insert_cassette(name, options = {})
USED_CASSETTES << VCR::Cassette.new(name, options).file
super
end
end
VCR.extend(CassetteReporter)
RSpec.configure do |config|
config.after(:suite) do
cassettes = Dir['vcr_cassettes/*.yml'].map { |d| File.expand_path(d) } - USED_CASSETTES.to_a
if cassettes.any?
puts "\nUnused cassettes:"
puts cassettes.map { |f| File.basename(f) }
end
end
end
@rafaelgonzalez
Copy link

This is helpful, thanks!

I have refined it so that:

  • there isn't a global constant defined for tracking used cassettes
  • whatever path configured for cassettes is used dynamically
  • .yml files in sub directories can are grabbed if like me you like to configure VCR to separate things in directories
module UsedCassetteReporter
  USED_CASSETTES = Set.new

  def insert_cassette(name, options = {})
    USED_CASSETTES << VCR::Cassette.new(name, options).file
    super
  end
end

RSpec.configure do |config|
  config.after(:suite) do
    all_cassettes = Dir[File.join(VCR::Cassette::Persisters::FileSystem.storage_location, '**', '*.yml')].map do |d|
      File.expand_path(d)
    end

    unused_cassettes = all_cassettes - UsedCassetteReporter::USED_CASSETTES.to_a

    if unused_cassettes.any?
      puts "\nUnused cassettes:"
      puts unused_cassettes
    end
  end
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment