How To Mock External APIs In Rails Tests
Learn how to mock external APIs in Rails tests with WebMock, VCR, and Minitest. Build fast, reliable tests for third-party APIs.
By Jean Emmanuel Cadet • 31 min read
Your test suite passed on Friday. On Monday morning, CI is red, and the failing test has nothing to do with the code you changed. The shipping provider was slow, a sandbox endpoint returned a 502, or a rate limit kicked in because three developers pushed at the same time. You rerun the build, it passes, and you quietly lose a little trust in your tests.
This is the exact problem that learning how to mock external APIs in Rails tests solves. When your automated tests depend on a third-party service, they inherit that service's slowness, outages, and surprises. When you isolate those calls, your tests become fast, deterministic, and free to run a thousand times a day.
In this guide, we will build a small shipping API client, then test it with WebMock, VCR, and Rails Minitest. We will also cover failure scenarios like timeouts and HTTP 429 responses, compare mocking with sandbox testing, and finish with a practical recommendation for a typical Rails application.
Why Mock External APIs in Rails Tests?
Rails Apps Depend on Outside Services
Almost every real Rails application talks to something it does not own. Payment providers charge cards, email services deliver messages, shipping APIs calculate rates and print labels, and third-party data providers return weather, addresses, or exchange rates. Your application code sits in the middle, translating between your domain and each provider's HTTP API.
That translation layer is your code, and it deserves tests. The question is how to test it without involving the outside world every time.
What Goes Wrong with Real HTTP Requests in Tests
Letting your test suite make real HTTP requests causes four distinct problems.
Speed. A network round trip takes tens or hundreds of milliseconds, and some providers take seconds. Multiply that by hundreds of tests and your feedback loop slows from seconds to minutes. Slow suites get run less often, and that is how bugs slip through.
Reliability. A test that fails because a provider had a bad five minutes is a flaky test. Flaky tests teach teams to ignore red builds, which is far more expensive than any single outage. Your tests should not depend on the availability of a third-party service that you cannot control.
Cost. Some APIs charge per request, and some enforce strict rate limits. A busy CI server running parallel builds can burn through a quota or generate real charges. Even a sandbox environment can throttle you once the suite grows.
Reproducibility. Real services return data that changes: new rates, new timestamps, new records. A test that passes today against live data might fail tomorrow with no code change. Good tests give the same answer every time they run.
Your Integration Logic Is Not the Provider
There is an important distinction hiding here. When you write a test for an API client, you are testing your application's integration logic: do you build the right request, send the right headers, parse the response correctly, and handle errors sensibly?
You are not testing whether the provider's servers work. That is the provider's job, and you cannot fix it anyway. Mocking draws that boundary clearly. Your tests control what the "provider" says, so you can focus entirely on how your code reacts.
Understanding Mocking, Stubbing, and Faking
What Mocking Means
In everyday conversation, developers use "mocking" to describe replacing a real dependency with a controlled substitute during a test. Strictly speaking, that is only one flavor of substitution. The broader umbrella term is test double, borrowed from the idea of a stunt double in a movie. A test double stands in for a real object so your test can run in isolation.
Stubs, Mocks, and Fakes
The vocabulary matters because each type answers a different question.
- A stub returns canned answers. It does not care how it was called.
- A mock (or spy) records how it was called so the test can verify the interaction.
- A fake is a lightweight working implementation, such as an in-memory version of a service.
Here are all three, written as plain Ruby objects against the ShippingClient we will build in the next section. No libraries are involved yet.
# A stub: always answers the same way
class StubShippingClient
def rates(postal_code:, weight_grams:)
[ ShippingClient::Rate.new(service: "standard", amount_cents: 599, currency: "USD", estimated_days: 5) ]
end
end
# A mock-style double: records the calls it receives
class RecordingShippingClient
attr_reader :shipments
def initialize
@shipments = []
end
def create_shipment(order_reference:, postal_code:, service:)
@shipments << { order_reference:, postal_code:, service: }
"TRACK-TEST-1"
end
end
# A fake: a tiny working implementation with simple rules
class FakeShippingClient
def rates(postal_code:, weight_grams:)
raise ShippingClient::Error, "Unknown postal code" unless postal_code.match?(/\A\d{5}\z/)
cents = 500 + (weight_grams / 100) * 10
[ ShippingClient::Rate.new(service: "standard", amount_cents: cents, currency: "USD", estimated_days: 5) ]
end
end
The stub is the simplest. The recording double lets a test ask, "Did the checkout actually request a shipment?" The fake behaves enough like the real thing that many tests can use it without special setup.
Verify the Call or Verify the Behavior?
A good rule of thumb: prefer verifying behavior over verifying calls. If your code asks for shipping rates and displays the cheapest one, the meaningful assertion is that the cheapest rate is displayed. Asserting that rates was called exactly once with specific arguments ties your test to implementation details that may change during a refactor.
Verifying that a call happened makes sense when the call itself is the observable outcome, because there is nothing to read back. "Creating an order sends exactly one shipment request" is a good example, since a duplicate request means a duplicate shipment in the real world.
Isolating the External Dependency
All of this depends on a seam: a clear place in your code where the outside world begins. If HTTP calls are scattered across controllers, models, and jobs, you have no good place to substitute anything. If they live behind one small client class, you can replace that class with a double, or intercept its HTTP traffic one level lower. Both options are available when the boundary is clean, and the next section shows how to build it.
How Rails Applications Make External HTTP Requests
Common HTTP Options in Ruby
Rails itself does not prescribe an HTTP client for outgoing requests. Ruby's standard library ships Net::HTTP, and many teams use gems such as Faraday, HTTParty, or HTTP.rb. Some providers publish official Ruby SDKs that hide the HTTP layer entirely. Nothing here is wrong, and your project might use any of them.
For this article, we use Net::HTTP because it requires no extra dependency and every Ruby developer can read it. WebMock hooks into Net::HTTP and several other popular HTTP libraries, so the testing approach carries over. Check the WebMock README for the full list of supported libraries if you use something else. The same advice applies to VCR, which works through WebMock in this article.
Keep API Communication Behind a Dedicated Client
Here is the client we will use throughout the article. It talks to a fictional shipping provider at a placeholder domain. It has two methods, rates and create_shipment, and it translates every failure into one of our own error classes.
# app/services/shipping_client.rb
require "net/http"
require "json"
class ShippingClient
class Error < StandardError; end
class ConnectionError < Error; end
class TimeoutError < Error; end
class AuthenticationError < Error; end
class ServerError < Error; end
class InvalidResponseError < Error; end
class RateLimitError < Error
attr_reader :retry_after
def initialize(message = "Rate limit exceeded", retry_after: nil)
super(message)
@retry_after = retry_after
end
end
Rate = Data.define(:service, :amount_cents, :currency, :estimated_days)
BASE_URL = "https://api.shipping-provider.example".freeze
OPEN_TIMEOUT = 2
READ_TIMEOUT = 5
def initialize(api_key: ENV.fetch("SHIPPING_API_KEY"), base_url: BASE_URL)
@api_key = api_key
@base_url = base_url
end
def rates(postal_code:, weight_grams:)
payload = get("/v1/rates", postal_code: postal_code, weight_grams: weight_grams)
rates = payload["rates"] if payload.is_a?(Hash)
raise InvalidResponseError, "Response is missing a rates array" unless rates.is_a?(Array)
rates.map { |attrs| build_rate(attrs) }
end
def create_shipment(order_reference:, postal_code:, service:)
payload = post("/v1/shipments", order_reference:, postal_code:, service:)
tracking_number = payload["tracking_number"] if payload.is_a?(Hash)
raise InvalidResponseError, "Response is missing a tracking number" if tracking_number.to_s.empty?
tracking_number
end
private
def get(path, **query)
uri = build_uri(path, query)
perform(Net::HTTP::Get.new(uri), uri)
end
def post(path, **body)
uri = build_uri(path)
request = Net::HTTP::Post.new(uri)
request["Content-Type"] = "application/json"
request.body = body.to_json
perform(request, uri)
end
def build_uri(path, query = {})
uri = URI.join(@base_url, path)
uri.query = URI.encode_www_form(query) unless query.empty?
uri
end
def perform(request, uri)
request["Authorization"] = "Bearer #{@api_key}"
request["Accept"] = "application/json"
response = Net::HTTP.start(
uri.host, uri.port,
use_ssl: uri.scheme == "https",
open_timeout: OPEN_TIMEOUT,
read_timeout: READ_TIMEOUT
) { |http| http.request(request) }
handle_response(response)
rescue Net::OpenTimeout, Net::ReadTimeout => e
raise TimeoutError, "Shipping API timed out (#{e.class})"
rescue SocketError, SystemCallError, OpenSSL::SSL::SSLError => e
raise ConnectionError, "Could not connect to the shipping API (#{e.class})"
end
def handle_response(response)
case response.code.to_i
when 200..299 then parse_json(response.body)
when 401, 403 then raise AuthenticationError, "Shipping API rejected the credentials"
when 429 then raise RateLimitError.new(retry_after: response["Retry-After"]&.to_i)
when 500..599 then raise ServerError, "Shipping API returned #{response.code}"
else raise Error, "Unexpected response from shipping API (#{response.code})"
end
end
def parse_json(body)
JSON.parse(body.to_s)
rescue JSON::ParserError
raise InvalidResponseError, "Response body was not valid JSON"
end
def build_rate(attrs)
raise InvalidResponseError, "A rate in the response was not an object" unless attrs.is_a?(Hash)
Rate.new(
service: attrs.fetch("service"),
amount_cents: Integer(attrs.fetch("amount_cents")),
currency: attrs.fetch("currency"),
estimated_days: attrs.fetch("estimated_days")
)
rescue KeyError, ArgumentError, TypeError
raise InvalidResponseError, "A rate in the response had an unexpected shape"
end
end
A few choices are worth pointing out. Every error class lives inside ShippingClient, which keeps the file compatible with Rails autoloading (one top-level constant per file). Explicit open and read timeouts mean a hung provider cannot hang your request forever. And the rest of the application only ever rescues ShippingClient::Error, so it never needs to know whether Net::HTTP, Faraday, or something else sits underneath.
This is why a dedicated client makes testing easier: there is exactly one place where HTTP happens, and exactly one set of error types to assert against.
Credentials Without Exposing Secrets
The client reads its API key from an environment variable by default. You could just as well use Rails encrypted credentials, for example Rails.application.credentials.dig(:shipping, :api_key). Both approaches keep the secret out of source code.
Notice that the key is also a constructor argument. In tests we pass a fake value like "test-api-key", so the suite never needs a real credential and never reads one from the environment by accident. Never commit real keys, .env files, or config/master.key to version control.
Mocking HTTP Requests with WebMock
What WebMock Solves
WebMock is a third-party gem, and it is not included with Rails. It intercepts outgoing HTTP requests at the library level, lets you declare which requests you expect and what to answer, and raises an error for anything you did not declare. That last part is the real safety net: a forgotten stub fails loudly instead of silently calling a real service.
Installing and Configuring WebMock
Add the gem to the :test group of your Gemfile:
group :test do
gem "webmock"
end
Then install it:
bundle install
Next, load it from test/test_helper.rb. This is Rails' default Minitest setup plus two lines at the bottom:
ENV["RAILS_ENV"] ||= "test"
require_relative "../config/environment"
require "rails/test_help"
require "webmock/minitest"
WebMock.disable_net_connect!(allow_localhost: true)
Requiring webmock/minitest integrates WebMock with Minitest and resets your stubs after every test. It already blocks real connections by default, but calling disable_net_connect! explicitly documents your intent and lets you configure exceptions in one visible place.
Stubbing a Request and Defining the Response
The core of WebMock is stub_request. You describe a request, then describe the response with to_return:
stub_request(:get, "https://api.shipping-provider.example/v1/rates")
.with(query: { postal_code: "10001", weight_grams: "750" })
.to_return(
status: 200,
headers: { "Content-Type" => "application/json" },
body: { rates: [ { service: "standard", amount_cents: 599, currency: "USD", estimated_days: 5 } ] }.to_json
)
Any code that sends a matching request now receives that response, with no network involved. The body must be a string, which is why we call to_json.
Matching URLs, Methods, Headers, Query Parameters, and Bodies
The first two arguments are the HTTP method and the URL. You can match a URL exactly, or use a regular expression when part of it varies:
stub_request(:get, %r{\Ahttps://api\.shipping-provider\.example/v1/shipments/\w+\z})
Use with to narrow the match. You can combine query parameters, headers, and bodies:
stub_request(:post, "https://api.shipping-provider.example/v1/shipments")
.with(
headers: { "Authorization" => "Bearer test-api-key", "Content-Type" => "application/json" },
body: { order_reference: "ORD-1001", postal_code: "10001", service: "standard" }
)
.to_return(status: 201, headers: { "Content-Type" => "application/json" }, body: { tracking_number: "TRACK123" }.to_json)
When the request has a JSON content type, WebMock can compare the body as a hash. When you only care about part of a payload, use hash_including, which works for both query strings and bodies:
.with(query: hash_including("postal_code" => "10001"))
.with(body: hash_including("service" => "standard"))
This is the tool for avoiding brittle tests: match what matters to the behavior, and ignore the rest.
Successful, Error, and Unexpected Responses
The same to_return method covers every response shape. A 404 or 500 is just a different status. An unexpected response is whatever the provider might actually send when something goes wrong, such as an HTML error page, an empty body, or JSON with missing fields:
stub_request(:get, url).to_return(status: 500, body: "Internal Server Error")
stub_request(:get, url).to_return(status: 200, body: "<html>Bad Gateway</html>")
stub_request(:get, url).to_return(status: 204, body: "")
You can also script a sequence of responses, which becomes essential for retry tests. After the last response in the sequence, WebMock keeps repeating it:
stub_request(:get, url)
.to_return(status: 503)
.then.to_return(status: 200, body: "{}")
For network-level failures, WebMock offers to_timeout and to_raise:
stub_request(:get, url).to_timeout
stub_request(:get, url).to_raise(Errno::ECONNREFUSED)
Preventing Unregistered External Requests
If a test triggers a request that you never stubbed, WebMock raises WebMock::NetConnectNotAllowedError, and the message includes a ready-to-paste stub_request snippet. There is a subtle detail that makes this error especially useful: it inherits from Exception, not StandardError. A careless rescue => e in your application code cannot swallow it, so a missing stub always surfaces as a failing test.
Allowing Local Connections Safely
Some tests legitimately need network access to your own machine. Rails system tests, for example, drive a browser that talks to a local Capybara server. That is what allow_localhost: true is for. If you use system tests, our guide on Rails System Tests: Test Real User Interactions covers the browser setup in depth.
If you need to allow a specific non-local host, such as a Dockerized browser, name it explicitly:
WebMock.disable_net_connect!(allow_localhost: true, allow: [ "selenium-hub" ])
The rule is simple: allow the narrowest thing that works, and never add a real API hostname to this list. If you do, you have quietly turned your safety net back into a hole.
Asserting That a Request Was Made
Sometimes the request itself is the outcome. WebMock provides assert_requested and assert_not_requested for these cases. Both work with Minitest after you require webmock/minitest:
assert_requested :post, "https://api.shipping-provider.example/v1/shipments", times: 1
assert_not_requested :post, "https://api.shipping-provider.example/v1/shipments"
Reserve these for cases where the call is the behavior, for instance, "a failed payment must not create a shipment."
Testing an API Client with WebMock
Setting Up the Test Class
Now we put everything together. This test file exercises ShippingClient without touching the network. It uses two small helpers: a rates_request method that builds the stub, and fetch_rates, which calls the client. Both keep the individual tests short and readable.
# test/services/shipping_client_test.rb
require "test_helper"
class ShippingClientTest < ActiveSupport::TestCase
RATES_URL = "https://api.shipping-provider.example/v1/rates".freeze
QUERY = { postal_code: "10001", weight_grams: "750" }.freeze
JSON_HEADERS = { "Content-Type" => "application/json" }.freeze
setup do
@client = ShippingClient.new(api_key: "test-api-key")
end
test "returns parsed rates for a successful response" do
rates_request.to_return(
status: 200,
headers: JSON_HEADERS,
body: {
rates: [
{ service: "standard", amount_cents: 599, currency: "USD", estimated_days: 5 },
{ service: "express", amount_cents: 1299, currency: "USD", estimated_days: 2 }
]
}.to_json
)
rates = fetch_rates
assert_equal %w[standard express], rates.map(&:service)
assert_equal 599, rates.first.amount_cents
end
private
def rates_request
stub_request(:get, RATES_URL).with(query: QUERY)
end
def fetch_rates
@client.rates(postal_code: "10001", weight_grams: 750)
end
end
The setup block builds the client with the fake "test-api-key". The success test verifies response parsing: the JSON becomes ShippingClient::Rate objects with the right values.
Verifying the Authentication Header
You can test that the client sends credentials without using a real key. The trick is to make the header part of the stub. If the client sends the wrong header, the stub will not match, and WebMock will raise instead of answering:
test "sends the API key as a bearer token" do
stub = stub_request(:get, RATES_URL)
.with(query: QUERY, headers: { "Authorization" => "Bearer test-api-key" })
.to_return(status: 200, headers: JSON_HEADERS, body: { rates: [] }.to_json)
fetch_rates
assert_requested stub
end
test "raises AuthenticationError when the provider rejects the key" do
rates_request.to_return(status: 401, body: { error: "invalid_token" }.to_json)
assert_raises(ShippingClient::AuthenticationError) { fetch_rates }
end
Malformed and Unexpected Responses
Providers sometimes return success status codes with bad payloads. Your client should convert those into a clear, domain-level error instead of crashing with a NoMethodError three layers away:
test "raises InvalidResponseError when the body is not JSON" do
rates_request.to_return(status: 200, body: "<html>Bad Gateway</html>")
assert_raises(ShippingClient::InvalidResponseError) { fetch_rates }
end
test "raises InvalidResponseError when the rates key is missing" do
rates_request.to_return(status: 200, headers: JSON_HEADERS, body: { data: [] }.to_json)
assert_raises(ShippingClient::InvalidResponseError) { fetch_rates }
end
test "raises InvalidResponseError when a rate has a non-numeric amount" do
rates_request.to_return(
status: 200,
headers: JSON_HEADERS,
body: { rates: [ { service: "standard", amount_cents: "free", currency: "USD", estimated_days: 5 } ] }.to_json
)
assert_raises(ShippingClient::InvalidResponseError) { fetch_rates }
end
Timeouts, Connection Errors, and HTTP Error Codes
Network failures and error statuses are just as easy to simulate, and they are the tests that teach you the most about your own error handling:
test "raises TimeoutError when the request times out" do
rates_request.to_timeout
assert_raises(ShippingClient::TimeoutError) { fetch_rates }
end
test "raises ConnectionError when the connection is refused" do
rates_request.to_raise(Errno::ECONNREFUSED)
assert_raises(ShippingClient::ConnectionError) { fetch_rates }
end
test "raises RateLimitError and exposes retry_after for HTTP 429" do
rates_request.to_return(status: 429, headers: { "Retry-After" => "30" })
error = assert_raises(ShippingClient::RateLimitError) { fetch_rates }
assert_equal 30, error.retry_after
end
[ 500, 502, 503 ].each do |status|
test "raises ServerError for HTTP #{status}" do
rates_request.to_return(status: status)
assert_raises(ShippingClient::ServerError) { fetch_rates }
end
end
Each test asserts an observable outcome, which is a specific error type with useful data, rather than checking which internal methods ran.
Keeping Tests Independent and Predictable
Every test above registers its own stub, and WebMock clears all stubs after each test. Nothing leaks from one test into the next, so tests can run in any order. Resist the temptation to define one big shared stub in a setup block and then override it in individual tests. That pattern makes it hard to tell which response a given test is actually seeing.
If your tests also need database records, keep that setup local and explicit too. Our comparison of FactoryBot vs. Fixtures: Testing Rails Applications can help you choose a data strategy that keeps tests readable alongside your API stubs.
Using VCR to Record and Replay HTTP Interactions
How VCR Differs from Manual Stubs
With WebMock, you write the fake response by hand. With VCR, you let a real request happen once, VCR saves the request and response to a file called a cassette, and every later run replays the cassette instead of touching the network.
VCR is also a third-party gem, and it is not included in Rails. In this setup it uses WebMock to intercept requests, so you install both.
The tradeoff is clear. Manual stubs are explicit, tiny, and fully controlled. Cassettes capture the exact shape of a real response, including fields you might not have thought to include, but they are larger, harder to read, and can go stale.
Installing and Configuring VCR with WebMock
Add VCR next to WebMock in the test group:
group :test do
gem "webmock"
gem "vcr"
end
Then configure it in test/test_helper.rb, after the WebMock lines:
require "vcr"
VCR.configure do |config|
config.cassette_library_dir = "test/cassettes"
config.hook_into :webmock
config.ignore_localhost = true
config.default_cassette_options = {
record: ENV["CI"] ? :none : :once,
match_requests_on: %i[method uri]
}
config.filter_sensitive_data("<SHIPPING_API_KEY>") { ENV["SHIPPING_API_KEY"] }
end
Here is what each setting does:
cassette_library_diris where recorded files are stored.hook_into :webmocktells VCR to intercept requests through WebMock.ignore_localhostlets local traffic, such as system test browsers, pass through.record: :oncerecords a cassette if the file does not exist and replays it afterward. In CI we use:none, which never records and fails if a request has no matching recording.match_requests_on: %i[method uri]matches by HTTP method and URL only. Headers are not compared, so replay still works when the recording used a real key and the test uses a fake one.filter_sensitive_datareplaces the real API key with a placeholder before the cassette is written. It also swaps the placeholder back during playback.
By default, VCR raises an error for any HTTP request made outside a cassette, which preserves the same safety net you had with WebMock.
Recording and Replaying with a Cassette
A cassette-backed test wraps the code in VCR.use_cassette:
# test/services/shipping_client_vcr_test.rb
require "test_helper"
class ShippingClientVcrTest < ActiveSupport::TestCase
test "parses rates from a recorded provider response" do
VCR.use_cassette("shipping_client/rates_nyc") do
client = ShippingClient.new(api_key: ENV.fetch("SHIPPING_API_KEY", "test-api-key"))
rates = client.rates(postal_code: "10001", weight_grams: 750)
assert rates.any?
assert_kind_of ShippingClient::Rate, rates.first
end
end
end
The first time you run this test, you provide a real sandbox key through your environment, and VCR writes test/cassettes/shipping_client/rates_nyc.yml. After that, anyone can run the test with no key and no network. A trimmed cassette looks like this:
http_interactions:
- request:
method: get
uri: https://api.shipping-provider.example/v1/rates?postal_code=10001&weight_grams=750
headers:
Authorization:
- Bearer <SHIPPING_API_KEY>
response:
status:
code: 200
message: OK
headers:
Content-Type:
- application/json
body:
string: '{"rates":[{"service":"standard","amount_cents":599,"currency":"USD","estimated_days":5}]}'
Notice the <SHIPPING_API_KEY> placeholder where the real token would have been.
Cassette Maintenance and Stale Recordings
Cassettes are snapshots, and snapshots age. If the provider adds a field, renames one, or changes behavior, your cassette keeps replaying the old shape and your tests keep passing against a reality that no longer exists.
To keep recordings honest, re-record them on purpose from time to time. Delete the cassette file and run the test with a valid sandbox key, then review the diff. VCR can also help: the re_record_interval option (in seconds) makes VCR re-record a cassette automatically when it is older than the interval and a network connection is available. That is convenient locally, but be careful with it in CI, where you generally want record: :none.
The Risks of Recording Real Responses
A cassette is a file written from a real conversation. That means it can contain tokens, cookies, email addresses, names, addresses, order details, and anything else the provider returned. Filtering the API key is only the beginning. Consider these precautions:
- Record against a sandbox account with fake data whenever the provider offers one.
- Use
filter_sensitive_datafor every secret, andbefore_recordhooks to strip headers likeSet-Cookie. - Open new cassettes and read them before committing. Search for tokens, emails, and personal data.
- If a cassette contains something sensitive, delete it, fix your filters, and record it again.
Never commit secrets or sensitive API responses to version control. Once something lands in Git history, removing it properly is painful.
When VCR Is Useful and When Manual Stubs Win
VCR shines when responses are large or complicated, when you are integrating with an API you do not know well yet, or when you want a realistic sample of what the provider actually returns. It is a poor fit for error scenarios. You cannot easily record a timeout or a 429 on demand, and a hand-written WebMock stub does those in one line. In practice, many teams use both: cassettes for a few happy-path samples, and manual stubs for everything else.
Using Rails Minitest and RSpec
What Belongs to Rails and What Belongs to the Gems
It helps to keep three layers separate in your head:
- Rails and Minitest provide the test framework:
ActiveSupport::TestCase,ActionDispatch::IntegrationTest,assert_equal,bin/rails test, and fixtures. - WebMock provides
stub_request,assert_requested, and request blocking. - VCR provides cassettes and
VCR.use_cassette.
WebMock and VCR are framework-agnostic. The framework only determines how you write test cases and assertions, which is why the same HTTP strategy works in Minitest and RSpec.
A Practical Minitest Example
Let us test code that uses the client, instead of the client itself. Here is a small service that picks the cheapest shipping rate and degrades gracefully when the provider is unavailable:
# app/services/shipping_quote.rb
class ShippingQuote
def initialize(client: nil)
@client = client || ShippingClient.new
end
def cheapest(postal_code:, weight_grams:)
@client.rates(postal_code: postal_code, weight_grams: weight_grams).min_by(&:amount_cents)
rescue ShippingClient::Error => e
Rails.logger.warn("Shipping rates unavailable: #{e.class}")
nil
end
end
The client: argument is a small seam for dependency injection, and it is also what lets us hand in a client with a fake key. The Minitest file stubs HTTP, and the service never knows the difference:
# test/services/shipping_quote_test.rb
require "test_helper"
class ShippingQuoteTest < ActiveSupport::TestCase
RATES_URL = "https://api.shipping-provider.example/v1/rates".freeze
QUERY = { postal_code: "10001", weight_grams: "750" }.freeze
setup do
client = ShippingClient.new(api_key: "test-api-key")
@quote = ShippingQuote.new(client: client)
end
test "returns the cheapest rate" do
stub_request(:get, RATES_URL).with(query: QUERY).to_return(
status: 200,
headers: { "Content-Type" => "application/json" },
body: {
rates: [
{ service: "express", amount_cents: 1299, currency: "USD", estimated_days: 2 },
{ service: "standard", amount_cents: 599, currency: "USD", estimated_days: 5 }
]
}.to_json
)
rate = @quote.cheapest(postal_code: "10001", weight_grams: 750)
assert_equal "standard", rate.service
end
test "returns nil when the provider times out" do
stub_request(:get, RATES_URL).with(query: QUERY).to_timeout
assert_nil @quote.cheapest(postal_code: "10001", weight_grams: 750)
end
end
The second test is the valuable one. It proves that a provider outage does not take your checkout down with it.
The Same Strategy with RSpec
If your project uses RSpec, the approach is identical. Add rspec-rails as usual, then require the RSpec integration of WebMock in spec/rails_helper.rb:
require "webmock/rspec"
WebMock.disable_net_connect!(allow_localhost: true)
Only the test syntax changes:
# spec/services/shipping_quote_spec.rb
require "rails_helper"
RSpec.describe ShippingQuote do
subject(:quote) { described_class.new(client: ShippingClient.new(api_key: "test-api-key")) }
it "returns nil when the provider times out" do
stub_request(:get, "https://api.shipping-provider.example/v1/rates")
.with(query: { postal_code: "10001", weight_grams: "750" })
.to_timeout
expect(quote.cheapest(postal_code: "10001", weight_grams: 750)).to be_nil
end
end
The stub_request and to_timeout lines are exactly what we wrote for Minitest. Only describe, it, and expect come from RSpec. VCR works the same way too: VCR.use_cassette is plain Ruby, and VCR also offers an optional RSpec metadata integration through configure_rspec_metadata! if you prefer tagging examples with :vcr.
Testing External API Failure Scenarios
Why Failure Tests Matter as Much as Success Tests
Happy-path tests prove your code works when everything goes right. But external services fail in ordinary, predictable ways: connections drop, servers return 500, rate limits trigger, and responses arrive in unexpected shapes. Production traffic will hit every one of these eventually. If you have never exercised those paths in a test, the first time they run will be in front of a real customer.
Mocking makes failure testing cheap. You cannot ask a real provider to time out on demand, but a stub does it instantly. We already covered timeouts and connection errors in the client tests, so let us look at the remaining scenarios.
Rate Limits and Server Errors
An HTTP 429 means the provider is telling you to slow down, often with a Retry-After header. The client test above verifies that we parse the header and raise a specific RateLimitError. A 500-class response is a different kind of failure: the provider has a problem, and a retry might succeed. Giving each case its own error class lets calling code make different decisions, such as showing a "try again shortly" message for a 429 and falling back to a flat shipping rate for a 500.
Do not confuse this with protecting your own application from abusive traffic. If you want to throttle incoming requests, see our article on Rails Rate Limiting: Protect Your App from Abuse. Here we are only handling the limits that someone else imposes on us.
Invalid JSON and Unexpected Formats
We tested three variants earlier: a body that is not JSON, a JSON object with the wrong shape, and a rate with a bad value. The goal is the same in each case: translate surprising input into one well-named error at the boundary. Without that, a nil from a missing key travels deep into your application before blowing up with an unhelpful message.
Retrying Without Slow or Flaky Tests
Retries are where tests tend to become slow, because a naive implementation calls sleep between attempts. The fix is to inject the waiting behavior, just like we injected the API key. Here are the changes to ShippingClient:
def initialize(api_key: ENV.fetch("SHIPPING_API_KEY"), base_url: BASE_URL,
max_attempts: 1, sleeper: ->(seconds) { sleep(seconds) })
@api_key = api_key
@base_url = base_url
@max_attempts = max_attempts
@sleeper = sleeper
end
def rates(postal_code:, weight_grams:)
payload = with_retries { get("/v1/rates", postal_code: postal_code, weight_grams: weight_grams) }
rates = payload["rates"] if payload.is_a?(Hash)
raise InvalidResponseError, "Response is missing a rates array" unless rates.is_a?(Array)
rates.map { |attrs| build_rate(attrs) }
end
private
def with_retries
attempts = 0
begin
attempts += 1
yield
rescue TimeoutError, ServerError, RateLimitError => error
raise if attempts >= @max_attempts
@sleeper.call(backoff_for(error, attempts))
retry
end
end
def backoff_for(error, attempt)
if error.is_a?(RateLimitError) && error.retry_after
error.retry_after
else
0.5 * (2**(attempt - 1))
end
end
The default of max_attempts: 1 means no retries, so every earlier test behaves exactly as before. We only retry the rates lookup, which is a read. Retrying create_shipment blindly could create duplicate shipments unless the provider supports idempotency keys, so think carefully before wrapping write requests.
Now the tests collect the sleeps instead of performing them, so they finish instantly:
test "retries a 503 and then succeeds" do
sleeps = []
client = ShippingClient.new(api_key: "test-api-key", max_attempts: 3, sleeper: ->(seconds) { sleeps << seconds })
stub = rates_request
.to_return(status: 503)
.then.to_return(status: 200, headers: JSON_HEADERS, body: { rates: [] }.to_json)
assert_equal [], client.rates(postal_code: "10001", weight_grams: 750)
assert_requested stub, times: 2
assert_equal [ 0.5 ], sleeps
end
test "honors Retry-After on a 429 and then succeeds" do
sleeps = []
client = ShippingClient.new(api_key: "test-api-key", max_attempts: 2, sleeper: ->(seconds) { sleeps << seconds })
rates_request
.to_return(status: 429, headers: { "Retry-After" => "2" })
.then.to_return(status: 200, headers: JSON_HEADERS, body: { rates: [] }.to_json)
client.rates(postal_code: "10001", weight_grams: 750)
assert_equal [ 2 ], sleeps
end
test "gives up after the maximum number of attempts" do
client = ShippingClient.new(api_key: "test-api-key", max_attempts: 3, sleeper: ->(_seconds) {})
stub = rates_request.to_return(status: 503)
assert_raises(ShippingClient::ServerError) do
client.rates(postal_code: "10001", weight_grams: 750)
end
assert_requested stub, times: 3
end
These tests check the retry policy directly: how many attempts, which waits, and what happens at the limit. In a real application, also consider capping Retry-After so a provider cannot make a web request sleep for minutes. For long waits, move the work to a background job instead.
Mocking vs. Using a Dedicated Test or Sandbox API
Two Different Kinds of Confidence
Mocked tests and sandbox tests answer different questions.
A mocked test says: "Given this response, my code behaves correctly." It runs in milliseconds, covers failure modes on demand, and never changes. But it can only verify your assumptions about the provider. If the provider's real behavior differs from your stub, the test happily stays green.
A sandbox test says: "The provider really accepts my request and returns something my code can parse." It catches contract drift, authentication mistakes, and wrong field names. But it is slower, depends on the network, may be rate limited, and cannot easily produce a timeout or a 500 on demand.
Keep Sandbox Tests in a Small Layer
Because sandbox tests are slower and less reliable, they belong in a small, separate layer rather than your main suite. Think of them as contract checks: a handful of tests that confirm the provider still behaves the way your stubs assume. You can skip them unless the right credentials are present, and run them on a schedule, such as nightly:
# test/provider/shipping_sandbox_test.rb
require "test_helper"
class ShippingSandboxTest < ActiveSupport::TestCase
setup do
skip "Set SHIPPING_SANDBOX_KEY to run provider checks" if ENV["SHIPPING_SANDBOX_KEY"].blank?
WebMock.allow_net_connect!
end
teardown do
WebMock.disable_net_connect!(allow_localhost: true)
end
test "sandbox rates match the shape our client expects" do
client = ShippingClient.new(
api_key: ENV.fetch("SHIPPING_SANDBOX_KEY"),
base_url: ENV.fetch("SHIPPING_SANDBOX_URL")
)
rates = client.rates(postal_code: "10001", weight_grams: 750)
assert rates.any?
assert rates.all? { |rate| rate.amount_cents.positive? }
end
end
If VCR is active in your suite, wrap the body in VCR.turned_off { ... } so VCR does not intercept the request.
A Practical Combination
A healthy approach looks like this: a large number of fast WebMock-based tests for client behavior and failure handling, a few cassettes for realistic samples, and a tiny set of sandbox checks that run outside the normal pull request flow. When a sandbox check fails, you update your stubs to match the new reality, and the fast tests keep protecting you.
Common Mistakes and Best Practices
Accidentally Allowing Real HTTP Requests
The most common mistake is leaving a hole in the safety net, such as a broad allow: list or a global WebMock.allow_net_connect! left over from debugging. Keep disable_net_connect! in test_helper.rb, allow only localhost, and treat any new allowance as a code review topic.
Writing Mocks That Do Not Match the Real Contract
A stub is a claim about how the provider behaves. If you invent a response shape from memory, your tests can pass while production fails. Copy response shapes from the provider's documentation or from a real sandbox response, and use your contract checks to catch drift.
Mocking Too Much Internal Behavior
Stubbing your own private methods or chains of objects makes tests brittle and meaningless. Stub at the boundary, which is the HTTP layer or your client class, and let everything inside your application run for real.
Using Real Keys or Sensitive Data in Fixtures
Fixtures and stubs should use obviously fake values like "test-api-key" and made-up names and addresses. Real values in test files tend to spread into Git history, logs, and screenshots.
Creating Brittle Tests
If a test fails because of a header you never cared about, the test is too strict. Match the details that define the behavior, such as the URL, method, and authentication, and use hash_including for partial bodies and queries.
Reusing Mutable Stubs Across Unrelated Tests
Shared stubs defined in a global setup make it hard to see what each test depends on. Define stubs inside the tests that need them. Also remember that WebMock's stub registry is global to the Ruby process. Rails' default process-based parallelization is fine, but if you switch to thread-based parallel tests, be careful about stubs interfering with each other.
Recording Sensitive Information in VCR Cassettes
Configure filter_sensitive_data before the first recording, and read every new cassette before committing it. A filter added after the fact does not clean up files that already exist.
Failing to Test Error and Timeout Scenarios
If your suite only contains happy paths, you are testing the easy half of your integration. Add at least a timeout, a 429, a 500, and a malformed body for every client.
Keeping API Clients Small and Focused
A client should build requests, send them, and translate responses and failures. Business decisions, like which shipping option to show a customer, belong in a separate object such as ShippingQuote. Small clients are easy to test thoroughly.
Testing Observable Behavior
Assert on returned values, raised errors, and user-visible outcomes. Avoid asserting on how many private methods were called or in what order. Tests that describe behavior survive refactoring, and tests that describe implementation do not.
Choosing the Right Mocking Strategy
When WebMock Is the Right Choice
WebMock is the best default for most API client tests. It gives you explicit control over every response, makes failure scenarios trivial, and keeps tests readable because the expected data sits next to the assertion. Choose it when you are testing your own client's behavior.
When VCR Is Useful
Choose VCR when responses are large or intricate, when you are exploring an unfamiliar API, or when you want realistic samples without hand-writing huge JSON bodies. Accept the maintenance cost: cassettes need review, re-recording, and careful filtering.
When Simple Stubs or Fakes Are Enough
Not every test needs HTTP-level interception. When you test code that merely uses the client, such as a checkout flow, a background job, or a view, a plain stub or a FakeShippingClient passed in through dependency injection is often simpler and faster. Save the HTTP-level tests for the client itself.
A Quick Comparison
Situation | Best fit | Why |
|---|---|---|
Testing the API client's requests and error handling | WebMock | Full control over requests and responses |
Testing failures like timeouts, 429, and 500 | WebMock | Easy to simulate on demand |
Capturing a realistic, complex response sample | VCR | Records the real shape once |
Testing code that consumes the client | Stub or fake client | No HTTP knowledge needed |
Verifying the provider still matches your assumptions | Sandbox contract test | Only a real call can confirm it |
A Practical Recommendation for a Typical Rails App
Start with WebMock and Minitest. Wrap each provider behind one small client, test it thoroughly with stubs, and use injected fakes in higher-level tests. Add VCR only where a realistic recorded sample earns its keep, and add a tiny scheduled sandbox check per critical provider. That combination gives you speed, reliability, and enough confidence that your assumptions still hold.
Conclusion
Isolating external API calls is one of the highest-leverage improvements you can make to a Rails test suite. Tests become faster because there is no network, more reliable because no third-party outage can break them, cheaper because nothing is billed or rate limited, and reproducible because the "provider" says the same thing every time.
Remember that success responses are only half the story. Timeouts, 429s, 500s, and malformed payloads are normal events for any integration, and mocking is what lets you test them without drama. Keep sandbox checks small and separate, filter every secret out of cassettes, and keep your clients focused.
You do not need to rewrite your whole suite at once. Pick one external API client, put it behind a small class, block real HTTP in test_helper.rb, and write your first stubbed test today. Then expand the same approach to the rest of your integrations, one client at a time.