VCR Cassettes in Rails: Recording, Replaying, and Managing HTTP Interactions
The VCR gem records real HTTP interactions to YAML cassette files and replays them in subsequent test runs, giving you fast, deterministic tests without live network calls. This post covers cassette strategies, sensitive data filtering, cassette lifecycle management, and when to choose VCR over WebMock stubs.
Tests that make real HTTP calls are slow, flaky, and expensive. An external API going down at 2am shouldn't fail your CI build. But full WebMock stubs require you to maintain fake responses manually—a maintenance burden that grows with every API version change.
VCR sits between these extremes: record real responses once, then replay them. The cassettes live in version control, your tests run offline, and refreshing them is a single command. This post covers the patterns that make VCR manageable in a production Rails codebase.
Setup
# Gemfile
gem "vcr", group: :test
gem "webmock", group: :test # VCR uses WebMock to intercept requests# spec/support/vcr.rb
require "vcr"
VCR.configure do |config|
config.cassette_library_dir = "spec/cassettes"
config.hook_into :webmock
config.configure_rspec_metadata!
# Ignore localhost (Capybara, internal calls)
config.ignore_localhost = true
# Allow real connections to localhost
config.allow_http_connections_when_no_cassette = false
# Filter sensitive values
config.filter_sensitive_data("<STRIPE_SECRET_KEY>") { ENV["STRIPE_SECRET_KEY"] }
config.filter_sensitive_data("<SENDGRID_API_KEY>") { ENV["SENDGRID_API_KEY"] }
config.filter_sensitive_data("<GITHUB_TOKEN>") { ENV["GITHUB_TOKEN"] }
config.filter_sensitive_data("<AUTH_HEADER>") do |interaction|
interaction.request.headers["Authorization"]&.first
end
endBasic Usage
RSpec Metadata Integration
After config.configure_rspec_metadata!, tag any example or group with :vcr to automatically use a cassette:
RSpec.describe StripeService, :vcr do
it "creates a customer" do
customer = StripeService.create_customer(email: "test@example.com")
expect(customer.id).to start_with("cus_")
end
endVCR derives the cassette name from the spec description hierarchy: spec/cassettes/StripeService/creates_a_customer.yml
Override the cassette name for shared cassettes:
it "fetches user data", vcr: { cassette_name: "github/user_response" } do
data = GithubClient.new.fetch_user("octocat")
expect(data["login"]).to eq("octocat")
endExplicit Cassette Blocks
For service objects tested in isolation, explicit blocks give you more control:
RSpec.describe WeatherService do
describe "#current_conditions" do
it "returns temperature and humidity" do
VCR.use_cassette("weather/london_current") do
conditions = WeatherService.new.current_conditions("London")
expect(conditions[:temperature]).to be_a(Numeric)
expect(conditions[:humidity]).to be_between(0, 100)
end
end
end
endRecord Modes
VCR's record modes control when cassettes are created or updated. Choosing the right one for each situation prevents stale cassettes and unnecessary network calls.
VCR.use_cassette("name", record: :mode) { ... }| Mode | Behavior | Use When |
|---|---|---|
:none |
Never record; raise if cassette doesn't exist | Production CI—no surprises |
:new_episodes |
Record new requests; replay existing ones | Adding endpoints to existing cassette |
:once |
Record once; raise if cassette exists but request isn't recorded | Default—safe for most specs |
:all |
Always record; overwrite cassette | Refreshing stale cassettes |
Recommended Configuration by Environment
VCR.configure do |config|
# In CI, never allow recording—all cassettes must exist
default_record_mode = ENV["CI"] ? :none : :once
config.default_cassette_options = {
record: default_record_mode,
match_requests_on: [:method, :uri, :body]
}
endRefreshing Cassettes
When the API changes, delete the cassette file and run the spec with network access:
# Delete a specific cassette
rm spec/cassettes/stripe/create_customer.yml
# Re-record by running the spec (not in CI mode)
bundle exec rspec spec/services/stripe_service_spec.rb
# Or use :all mode to overwrite all cassettes
VCR_RECORD=all bundle exec rspecAdd a helper for re-recording:
# spec/support/vcr.rb
record_mode = case ENV["VCR_RECORD"]
when "all" then :all
when "new" then :new_episodes
else (ENV["CI"] ? :none : :once)
end
config.default_cassette_options = { record: record_mode }Sensitive Data Filtering
Never commit cassettes with real API keys, tokens, or personal data. VCR's filter_sensitive_data replaces sensitive values with placeholders before writing to disk.
Filtering Request Headers
VCR.configure do |config|
# Replace Authorization header value
config.filter_sensitive_data("<BEARER_TOKEN>") do |interaction|
interaction.request.headers["Authorization"]&.first
end
# Replace API key in query strings
config.filter_sensitive_data("<API_KEY>") do |interaction|
uri = URI(interaction.request.uri)
params = URI.decode_www_form(uri.query || "").to_h
params["api_key"]
end
endFiltering Response Bodies
For APIs that echo back sensitive data in responses:
VCR.configure do |config|
# Filter PII from response bodies
config.before_record do |interaction|
body = interaction.response.body
# Replace real email addresses with placeholder
interaction.response.body = body.gsub(/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/i, "filtered@example.com")
end
endFiltering Dynamic Values
Some responses include dynamic values (timestamps, request IDs) that would cause cassette mismatches. Normalize them:
VCR.configure do |config|
config.before_record do |interaction|
if interaction.response.headers["Content-Type"]&.first&.include?("application/json")
body = JSON.parse(interaction.response.body) rescue nil
if body.is_a?(Hash)
# Normalize timestamp fields
body["created_at"] = "2026-01-01T00:00:00Z" if body.key?("created_at")
body["request_id"] = "req_filtered" if body.key?("request_id")
interaction.response.body = body.to_json
end
end
end
endRequest Matching
VCR matches incoming requests to recorded interactions. The default matches on method and URI only. Customize matching when needed:
# Match on method, URI, and request body (for POST/PUT with JSON)
VCR.use_cassette("api/create", match_requests_on: [:method, :uri, :body]) do
# ...
end
# Custom matcher for GraphQL (same URI, different body)
VCR.configure do |config|
config.register_request_matcher(:graphql_operation) do |r1, r2|
body1 = JSON.parse(r1.body)
body2 = JSON.parse(r2.body)
body1["operationName"] == body2["operationName"]
end
config.default_cassette_options = {
match_requests_on: [:method, :uri, :graphql_operation]
}
endURI Normalization
When query parameter order is inconsistent, normalize URIs for matching:
VCR.configure do |config|
config.register_request_matcher(:normalized_uri) do |r1, r2|
normalize_uri(r1.uri) == normalize_uri(r2.uri)
end
def normalize_uri(uri)
parsed = URI.parse(uri)
params = URI.decode_www_form(parsed.query || "").sort
parsed.query = URI.encode_www_form(params)
parsed.to_s
end
endCassette Organization
A flat spec/cassettes/ directory becomes unmanageable quickly. Mirror your spec directory structure:
spec/
cassettes/
services/
stripe/
create_customer.yml
charge_card_success.yml
charge_card_declined.yml
github/
fetch_user.yml
list_repos.yml
sendgrid/
send_transactional.yml
integrations/
webhooks/
stripe_payment_succeeded.ymlUse a helper to build cassette names from the spec context:
def cassette_for(*parts)
parts.map { |p| p.to_s.parameterize.underscore }.join("/")
end
VCR.use_cassette(cassette_for("stripe", "create customer")) do
# => "spec/cassettes/stripe/create_customer.yml"
endVCR vs WebMock: When to Use Each
VCR and WebMock serve different purposes and work best together.
Use VCR when:
- Testing service objects or clients that wrap a specific external API
- The response structure matters to your code (parsing, error handling)
- You want to test against real API behavior recorded once
- You need to test multiple response scenarios from the same endpoint
Use WebMock directly when:
- Testing a piece of code that should call an API (verify the call was made, not the response)
- Simulating specific error conditions (timeouts, 500s, network failures)
- Unit testing code that uses HTTP but the response doesn't matter
- The cassette would require real credentials to record
# WebMock for verifying the call is made correctly
RSpec.describe NotificationService do
it "sends a webhook with the correct payload" do
stub = stub_request(:post, "https://hooks.example.com/notify")
.with(body: hash_including(event: "user.created"))
.to_return(status: 200, body: "{}", headers: { "Content-Type" => "application/json" })
NotificationService.notify(:user_created, user_id: 42)
expect(stub).to have_been_requested.once
end
end
# VCR for testing the response parsing
RSpec.describe GithubClient, :vcr do
it "parses repository data correctly" do
repos = GithubClient.new(token: "test").list_repos("octocat")
expect(repos.first).to have_key(:name)
expect(repos.first).to have_key(:clone_url)
end
endHandling Timeouts and Errors
WebMock handles error simulation better than VCR cassettes:
RSpec.describe StripeService do
context "when Stripe is unavailable" do
before do
stub_request(:post, %r{api\.stripe\.com})
.to_timeout
end
it "raises a PaymentGatewayError" do
expect {
StripeService.create_customer(email: "test@example.com")
}.to raise_error(PaymentGatewayError, /timeout/)
end
end
context "when Stripe returns 429" do
before do
stub_request(:post, %r{api\.stripe\.com})
.to_return(status: 429, headers: { "Retry-After" => "30" })
end
it "raises a RateLimitError" do
expect {
StripeService.create_customer(email: "test@example.com")
}.to raise_error(Stripe::RateLimitError)
end
end
endCassette Maintenance in CI
Keep cassettes auditable and prevent accidental recording in CI:
# spec/support/vcr.rb
VCR.configure do |config|
# Hard-fail in CI if a request would have been recorded
if ENV["CI"]
config.before_record do |interaction|
raise "VCR attempted to record in CI! Cassette missing or record mode wrong.\n" \
"Request: #{interaction.request.method.upcase} #{interaction.request.uri}"
end
end
endAdd to your CI workflow to verify no cassettes are accidentally modified:
# .github/workflows/test.yml
- name: Run specs
run: bundle exec rspec
- name: Check for uncommitted cassette changes
run: |
if ! git diff --quiet spec/cassettes/; then
echo "Cassette files were modified during CI run!"
git diff spec/cassettes/
exit 1
fiKey Takeaways
- Use
:nonerecord mode in CI—cassettes must exist before merge, never recorded during CI - Filter sensitive data before it hits disk: Authorization headers, API keys, and PII
- Normalize dynamic response fields (timestamps, request IDs) to prevent cassette drift
- Organize cassettes to mirror your spec directory structure
- Use
match_requests_on: [:method, :uri, :body]for APIs that use POST with different bodies - Use WebMock for error simulation and call verification; use VCR for response parsing tests
- Re-record cassettes periodically or when the API version changes—stale cassettes hide real bugs