Skip to content

Instantly share code, notes, and snippets.

@ttilberg
Last active August 4, 2023 15:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ttilberg/d83caa249623f520b9e3c47f4a76f5f0 to your computer and use it in GitHub Desktop.
Save ttilberg/d83caa249623f520b9e3c47f4a76f5f0 to your computer and use it in GitHub Desktop.
My MiniTest + VCR `with_vcr {}` selective recording configuration

Minitest Recordable

This small module sets up VCR in a way that makes using VCR in Minitest a breeze. You can wrap specific parts of your test in a with_vcr block that will automatically create and name a cassette and directory based on the test and class name, and handles nested names. It works great both from inside Rails, and not.

The example test file in this gist stores its results to test/vcr/Search_GoogleTest/test_search.yml.

# Minitest "plugin" to specify VCR recording for tests.
# This will automatically generate cassettes based on the test class and name.
#
module Minitest::Recordable
def with_vcr
VCR.insert_cassette cassette_dir
yield
VCR.eject_cassette
end
private
def cassette_dir
File.join(class_name, name)
end
end
class Search::GoogleTest < ActiveSupport::TestCase
test 'search' do
# `with_vcr` will save any requests made to a directory based on this files class and test name.
with_vcr do
results = Search::Google.new('55802').search
assert results.any? {|result| result.name == 'Discount Tire'}
end
end
end
ENV['RAILS_ENV'] ||= 'test'
require_relative '../config/environment'
require 'rails/test_help'
require_relative 'minitest_recordable'
class ActiveSupport::TestCase # or Minitest::Test
# ... Other boilerplate or not-so-boilerplate ...
# Include VCR/Webmock helpers for tests
include Minitest::Recordable
end
VCR.configure do |config|
config.cassette_library_dir = Rails.root.join('test/vcr')
config.hook_into :webmock
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment