Mocks and test doubles

suggest change

A test double is an object that stands in for a real one during a test. You use one when the real collaborator is slow (a network call), has side effects (sending email, charging a card), is hard to put into a given state (a server that returns 503), or isn't deterministic (the current time).

The names come from Gerard Meszaros' xUnit Test Patterns and are used by Minitest and RSpec:

Kind What it does
dummy passed around but never used (fills a required argument)
stub returns canned answers to calls
spy a stub that also records the calls, so the test can check them later
mock set up in advance with the calls it expects, fails if they don't happen
fake a working but simplified implementation (in-memory database, fake gateway)

In everyday speech "mock" often means any of these. The difference that matters in practice is between stubbing (control what a collaborator returns, then check the result of your code) and mocking (check that your code sent the right messages to a collaborator).

This article covers:

The examples were run with Ruby 4.0, Minitest 6.0 with minitest-mock 5.27, RSpec 3.13 and WebMock 3.34.

The code under test

All examples test this class. It charges a card through a payment gateway and then mails a receipt:

# checkout.rb
require "timeout"

class PaymentGateway
  # The real one talks to a payment provider over HTTP.
  def charge(amount_cents, card:)
    raise NotImplementedError, "real network call"
  end
end

class Mailer
  def deliver(to:, subject:, body:)
    raise NotImplementedError, "real SMTP call"
  end
end

class Checkout
  def initialize(gateway:, mailer:, clock: Time)
    @gateway = gateway
    @mailer = mailer
    @clock = clock
  end

  def place(order)
    result = @gateway.charge(order[:total], card: order[:card])
    return :declined unless result[:ok]

    @mailer.deliver(
      to: order[:email],
      subject: "Receipt #{result[:id]}",
      body: "Paid $#{format('%.2f', order[:total] / 100.0)} on #{@clock.now.strftime('%Y-%m-%d')}"
    )
    :paid
  rescue Timeout::Error
    :retry_later
  end
end

Checkout receives its collaborators through the constructor instead of creating them itself. That's dependency injection, and it is what makes doubles easy to use: a test passes a different object, and production code passes the real one. The clock: Time default means callers don't have to pass a clock, but a test can.

Hand-written doubles

Ruby is duck typed. Checkout doesn't care about the class of gateway, only that it responds to charge. So a double can be any object with the right methods, and you often don't need a library at all:

require "minitest/autorun"
require_relative "checkout"

# A stub: returns canned answers, records nothing.
class ApprovingGateway
  def charge(amount_cents, card:) = { ok: true, id: "ch_1" }
end

# A spy: records calls so the test can check them afterwards.
class MailerSpy
  attr_reader :sent

  def initialize = @sent = []
  def deliver(**message) = @sent << message
end

class CheckoutFakesTest < Minitest::Test
  ORDER = { total: 1999, card: "tok_visa", email: "ann@example.com" }

  def test_sends_receipt_when_payment_succeeds
    mailer = MailerSpy.new
    clock = Struct.new(:now).new(Time.new(2026, 10, 17))
    checkout = Checkout.new(gateway: ApprovingGateway.new, mailer: mailer, clock: clock)

    assert_equal :paid, checkout.place(ORDER)
    assert_equal 1, mailer.sent.size
    assert_equal "ann@example.com", mailer.sent.first[:to]
    assert_equal "Paid $19.99 on 2026-10-17", mailer.sent.first[:body]
  end

  def test_declined_payment_sends_nothing
    gateway = Object.new
    def gateway.charge(*, **) = { ok: false }
    mailer = MailerSpy.new

    assert_equal :declined, Checkout.new(gateway: gateway, mailer: mailer).place(ORDER)
    assert_empty mailer.sent
  end
end
Run options: --seed 49090

# Running:

..

Finished in 0.001467s, 1362.8620 runs/s, 4770.0170 assertions/s.

2 runs, 7 assertions, 0 failures, 0 errors, 0 skips

Three tricks are worth remembering:

A fake goes further and actually works, in a simplified way. Fakes are the best choice when many tests share a collaborator, because they keep state between calls the way the real thing does:

require "minitest/autorun"
require_relative "checkout"

# A fake: a working, simplified implementation.
class FakeGateway
  attr_reader :charges

  def initialize(declined_cards: [])
    @declined_cards = declined_cards
    @charges = []
  end

  def charge(amount_cents, card:)
    return { ok: false } if @declined_cards.include?(card)

    @charges << amount_cents
    { ok: true, id: "ch_#{@charges.size}" }
  end
end

class FakeGatewayContractTest < Minitest::Test
  def test_fake_matches_real_interface
    real = PaymentGateway.instance_method(:charge).parameters
    fake = FakeGateway.instance_method(:charge).parameters
    assert_equal real, fake
  end
end

class CheckoutWithFakeTest < Minitest::Test
  def test_two_orders_one_declined
    gateway = FakeGateway.new(declined_cards: ["tok_stolen"])
    mailer = Object.new
    def mailer.deliver(**) = nil
    checkout = Checkout.new(gateway: gateway, mailer: mailer)

    results = [
      checkout.place(total: 1000, card: "tok_visa", email: "a@example.com"),
      checkout.place(total: 2500, card: "tok_stolen", email: "b@example.com"),
    ]

    assert_equal [:paid, :declined], results
    assert_equal [1000], gateway.charges
  end
end
2 runs, 3 assertions, 0 failures, 0 errors, 0 skips

The danger of any hand-written double is drift: someone renames charge in the real class, the fake keeps the old name, and every test still passes while production is broken. FakeGatewayContractTest guards against that by comparing method signatures ([[:req, :amount_cents], [:keyreq, :card]]). RSpec's verified doubles, shown below, do the same check automatically.

Minitest::Mock

Minitest ships with a tiny mock library. Since Minitest 6 it lives in a separate gem, so add gem "minitest-mock" to your Gemfile (with Minitest 5 it's built in). In both cases you load it with require "minitest/mock".

You create a mock, declare each call you expect with expect(name, return_value, positional_args, **keyword_args), run the code, and then check that every expected call happened with assert_mock (or mock.verify):

require "minitest/autorun"
require "minitest/mock"
require_relative "checkout"

class CheckoutMockTest < Minitest::Test
  ORDER = { total: 1999, card: "tok_visa", email: "ann@example.com" }

  def test_charges_card_and_mails_receipt
    gateway = Minitest::Mock.new
    gateway.expect(:charge, { ok: true, id: "ch_1" }, [1999], card: "tok_visa")

    mailer = Minitest::Mock.new
    mailer.expect(:deliver, true) do |to:, subject:, body:|
      to == "ann@example.com" && subject == "Receipt ch_1" && body.start_with?("Paid $19.99")
    end

    assert_equal :paid, Checkout.new(gateway: gateway, mailer: mailer).place(ORDER)
    assert_mock gateway
    assert_mock mailer
  end
end
1 runs, 3 assertions, 0 failures, 0 errors, 0 skips

Expected arguments are compared with ===, so you can pass a class ([Integer], card: String) or a regexp instead of an exact value. When the check is more complicated, pass a block instead of an argument list: it receives the actual arguments, and the call is accepted if the block returns a truthy value.

Each expect allows one call. Calling a method twice requires two expect lines. Here is what the common mistakes look like:

def test_unexpected_arguments
  gateway = Minitest::Mock.new
  gateway.expect(:charge, { ok: false }, [500], card: "tok_visa")

  Checkout.new(gateway: gateway, mailer: nil).place(ORDER)
end

def test_missing_call
  gateway = Minitest::Mock.new
  gateway.expect(:charge, { ok: true, id: "ch_1" }, [Integer], card: String)
  mailer = Minitest::Mock.new
  mailer.expect(:deliver, true, to: String, subject: String, body: String)
  mailer.expect(:deliver, true, to: String, subject: String, body: String)

  Checkout.new(gateway: gateway, mailer: mailer).place(ORDER)
  assert_mock mailer
end
  1) Failure:
CheckoutMockTest#test_missing_call [mock_test.rb:37]:
Expected deliver(to: String, subject: String, body: String) => true, got [deliver(to: String, subject: String, body: String) => true].

  2) Error:
CheckoutMockTest#test_unexpected_arguments:
MockExpectationError: mocked method :charge called with unexpected arguments [1999]
    checkout.rb:25:in 'Checkout#place'
    mock_test.rb:26:in 'CheckoutMockTest#test_unexpected_arguments'

The first message means "two calls to deliver were expected, only one happened". Calling a method the mock knows nothing about raises NoMethodError: unmocked method :refund, expected one of [], and calling an expected method once too often raises MockExpectationError: No more expects available for :charge.

Minitest mocks are not thread-safe. If the code under test calls the double from another thread, use a hand-written spy instead.

Minitest stub

Object#stub (also from minitest/mock) temporarily replaces a method on an existing object or class for the duration of a block. It's the tool for code you can't inject, like Time.now:

require "minitest/autorun"
require "minitest/mock"
require_relative "checkout"

class CheckoutStubTest < Minitest::Test
  ORDER = { total: 1999, card: "tok_visa", email: "ann@example.com" }

  def setup
    @gateway = PaymentGateway.new
    @mailer = Mailer.new
    @checkout = Checkout.new(gateway: @gateway, mailer: @mailer)
  end

  def test_uses_current_date_in_receipt
    sent = nil
    @gateway.stub(:charge, { ok: true, id: "ch_1" }) do
      @mailer.stub(:deliver, ->(**msg) { sent = msg }) do
        Time.stub(:now, Time.new(2026, 1, 2)) do
          assert_equal :paid, @checkout.place(ORDER)
        end
      end
    end
    assert_equal "Paid $19.99 on 2026-01-02", sent[:body]
  end

  def test_gateway_timeout
    @gateway.stub(:charge, ->(*) { raise Timeout::Error }) do
      assert_equal :retry_later, @checkout.place(ORDER)
    end
  end

  def test_stub_is_removed_after_block
    Time.stub(:now, Time.at(0)) { assert_equal 1970, Time.now.utc.year }
    assert_operator Time.now.year, :>, 2000
  end
end
3 runs, 6 assertions, 0 failures, 0 errors, 0 skips

How stub(name, value) behaves:

stub doesn't check how many times or with what arguments the method was called. Combine it with a lambda that records calls (as above), or with a Minitest::Mock as the replacement value, when you need that.

RSpec doubles

rspec-mocks is part of RSpec and has more features than Minitest's mocks. double creates a blank object. allow(...).to receive stubs a method, and expect(...).to receive sets an expectation that is verified automatically at the end of the example:

require_relative "../checkout"

RSpec.describe Checkout do
  let(:order)   { { total: 1999, card: "tok_visa", email: "ann@example.com" } }
  let(:gateway) { double("gateway") }
  let(:mailer)  { double("mailer", deliver: true) }
  subject(:checkout) { described_class.new(gateway: gateway, mailer: mailer) }

  it "charges the card and mails a receipt" do
    allow(gateway).to receive(:charge).and_return({ ok: true, id: "ch_1" })

    expect(mailer).to receive(:deliver).with(
      to: "ann@example.com",
      subject: "Receipt ch_1",
      body: a_string_starting_with("Paid $19.99")
    )

    expect(checkout.place(order)).to eq(:paid)
  end

  it "charges the exact amount once" do
    expect(gateway).to receive(:charge).with(1999, card: "tok_visa").once
      .and_return({ ok: false })

    expect(checkout.place(order)).to eq(:declined)
  end

  it "does not mail anything when declined" do
    allow(gateway).to receive(:charge).and_return({ ok: false })
    expect(mailer).not_to receive(:deliver)

    checkout.place(order)
  end

  it "asks to retry when the gateway times out" do
    allow(gateway).to receive(:charge).and_raise(Timeout::Error)

    expect(checkout.place(order)).to eq(:retry_later)
  end
end
$ rspec --format documentation spec/checkout_spec.rb
Checkout
  charges the card and mails a receipt
  charges the exact amount once
  does not mail anything when declined
  asks to retry when the gateway times out

Finished in 0.05946 seconds (files took 0.63116 seconds to load)
4 examples, 0 failures

double("mailer", deliver: true) is a shortcut for creating a double and stubbing deliver to return true. The string is only a name used in error messages.

The building blocks combine freely:

Piece Meaning
.with(1999, card: "tok_visa") only match these arguments
.with(anything, hash_including(card: String)) argument matchers
.and_return(a) / .and_return(a, b, c) return value, or values for successive calls
.and_raise(Timeout::Error) raise an exception
.and_yield(obj) yield to the block passed by the caller
.and_call_original run the real method (partial doubles only)
receive(:double) { ... } a block computes the return value
.once, .twice, .exactly(3).times, .at_least(:once) call counts
.ordered calls must happen in this order

Any RSpec matcher can be used as an argument matcher: a_string_starting_with, a_value_between(1, 10), an_instance_of(Integer), kind_of(Numeric) and so on.

The failure messages say exactly what went wrong:

  1) failure messages unexpected message
     Failure/Error: Checkout.new(gateway: gateway, mailer: nil).place(order)
       #<Double "gateway"> received unexpected message :charge with (1999, {card: "tok_visa"})

  2) failure messages wrong arguments
     Failure/Error: Checkout.new(gateway: gateway, mailer: nil).place(order)

       #<Double "gateway"> received :charge with unexpected arguments
         expected: (2000, {card: "tok_visa"})
              got: (1999, {card: "tok_visa"})

  3) failure messages never called
     Failure/Error: expect(mailer).to receive(:deliver)

       (Double "mailer").deliver(*(any args))
           expected: 1 time with any arguments
           received: 0 times with any arguments

A plain double is strict: any message you didn't stub raises an error (failure 1). If you want a double that accepts anything and returns nil, use double.as_null_object or spy.

Spies: assert after the fact

expect(...).to receive must come before the code runs, which turns the usual arrange-act-assert order upside down. Spies restore it. Stub or spy on everything first, run the code, then check with have_received:

require_relative "../checkout"

RSpec.describe Checkout do
  let(:order) { { total: 1999, card: "tok_visa", email: "ann@example.com" } }

  it "mails a receipt (spy style)" do
    gateway = instance_double(PaymentGateway, charge: { ok: true, id: "ch_1" })
    mailer = instance_spy(Mailer)

    Checkout.new(gateway: gateway, mailer: mailer).place(order)

    expect(gateway).to have_received(:charge).with(1999, card: "tok_visa")
    expect(mailer).to have_received(:deliver)
      .with(hash_including(to: "ann@example.com"))
  end
end
1 example, 0 failures

have_received only works on methods that were stubbed (allow or the hash shortcut) or on a spy, which accepts every message. have_received accepts the same .with, .once and .ordered modifiers as receive.

Verified doubles

A plain double knows nothing about the class it replaces, so it has the same drift problem as a hand-written fake. instance_double(SomeClass) checks every stub against the real class: the method must exist and the arguments must fit its signature.

require_relative "../checkout"

RSpec.describe "verified doubles" do
  it "rejects methods the real class doesn't have" do
    gateway = instance_double(PaymentGateway)
    allow(gateway).to receive(:refund)
  end

  it "rejects wrong arguments" do
    gateway = instance_double(PaymentGateway)
    allow(gateway).to receive(:charge).and_return({ ok: false })
    gateway.charge(1999, "tok_visa")
  end
end
  1) verified doubles rejects methods the real class doesn't have
     Failure/Error: allow(gateway).to receive(:refund)
       the PaymentGateway class does not implement the instance method: refund

  2) verified doubles rejects wrong arguments
     Failure/Error: gateway.charge(1999, "tok_visa")

     ArgumentError:
       Missing required keyword arguments: card

There are verified variants of each kind of double:

Prefer them to plain double. Verification only happens when the class is loaded. If you pass the class name as a string (instance_double("PaymentGateway")) and the class isn't loaded, the double silently behaves like a plain one. That lets fast unit tests run without loading the whole app, but the full suite should load everything.

Partial doubles: stubbing real objects

allow and expect also work on real objects and classes. Only the methods you stub are replaced, the rest behave normally, and everything is restored after each example. RSpec calls these partial doubles:

require_relative "../checkout"

RSpec.configure do |config|
  config.mock_with :rspec do |mocks|
    mocks.verify_partial_doubles = true
  end
end

class Report
  def self.generate = "Report for #{Time.now.strftime('%B %Y')}"
end

RSpec.describe "partial doubles" do
  it "stubs a method on a real object" do
    allow(Time).to receive(:now).and_return(Time.new(2026, 3, 1))
    expect(Report.generate).to eq("Report for March 2026")
  end

  it "returns values in sequence, then repeats the last" do
    die = double("die")
    allow(die).to receive(:roll).and_return(6, 1, 3)
    expect(4.times.map { die.roll }).to eq([6, 1, 3, 3])
  end

  it "computes the result with a block" do
    calc = double("calc")
    allow(calc).to receive(:double) { |n| n * 2 }
    expect(calc.double(21)).to eq(42)
  end

  it "stubs only some arguments and calls the original for the rest" do
    allow(ENV).to receive(:fetch).and_call_original
    allow(ENV).to receive(:fetch).with("API_KEY").and_return("test-key")
    expect(ENV.fetch("API_KEY")).to eq("test-key")
    expect(ENV.fetch("NOPE_NOT_SET", "default")).to eq("default")
  end

  it "yields to the block" do
    file = double("file")
    allow(File).to receive(:open).with("config.txt").and_yield(file)
    allow(file).to receive(:read).and_return("debug=true")
    expect(File.open("config.txt") { |f| f.read }).to eq("debug=true")
  end

  it "checks call order" do
    db = double("db")
    expect(db).to receive(:begin).ordered
    expect(db).to receive(:insert).twice.ordered
    expect(db).to receive(:commit).ordered
    db.begin; db.insert; db.insert; db.commit
  end

  it "replaces a constant" do
    stub_const("Checkout::MAX_RETRIES", 0)
    expect(Checkout::MAX_RETRIES).to eq(0)
  end

  it "catches typos in partial doubles" do
    allow(Time).to receive(:nwo)
  end
end
.......F

Failures:

  1) partial doubles catches typos in partial doubles
     Failure/Error: allow(Time).to receive(:nwo)
       Time does not implement: nwo

8 examples, 1 failure

Notes:

Partial doubles also rescue code that creates its collaborators itself, so they can't be injected:

class LegacyCheckout
  def place(order)
    result = PaymentGateway.new.charge(order[:total], card: order[:card])
    result[:ok] ? :paid : :declined
  end
end

RSpec.describe LegacyCheckout do
  it "can still be tested by stubbing .new" do
    gateway = instance_double(PaymentGateway, charge: { ok: true })
    allow(PaymentGateway).to receive(:new).and_return(gateway)

    expect(LegacyCheckout.new.place(total: 500, card: "tok")).to eq(:paid)
    expect(gateway).to have_received(:charge).with(500, card: "tok")
  end
end

This works, but if you find yourself stubbing .new a lot, the code is asking to take its dependencies as arguments. Avoid allow_any_instance_of too. RSpec's own documentation discourages it, because it hides which object is involved and behaves oddly with inheritance and modules.

Stubbing HTTP with WebMock

For code that makes HTTP requests you can stub at a lower level instead of doubling your own classes. WebMock hooks into Net::HTTP and most other Ruby HTTP clients, returns canned responses, and blocks any request you haven't stubbed:

require "net/http"
require "json"
require "webmock/rspec"

class ExchangeRates
  def initialize(base_url = "https://rates.example.com")
    @base_url = base_url
  end

  def rate(from, to)
    res = Net::HTTP.get_response(URI("#{@base_url}/latest?from=#{from}&to=#{to}"))
    raise "rates API error: #{res.code}" unless res.is_a?(Net::HTTPSuccess)
    JSON.parse(res.body).dig("rates", to)
  end
end

RSpec.describe ExchangeRates do
  it "parses the rate" do
    stub_request(:get, "https://rates.example.com/latest")
      .with(query: { from: "USD", to: "EUR" })
      .to_return(body: '{"rates":{"EUR":0.92}}', headers: { "Content-Type" => "application/json" })

    expect(ExchangeRates.new.rate("USD", "EUR")).to eq(0.92)
  end

  it "raises on server errors" do
    stub_request(:get, /rates.example.com/).to_return(status: 503)
    expect { ExchangeRates.new.rate("USD", "EUR") }.to raise_error("rates API error: 503")
  end

  it "blocks unstubbed requests" do
    ExchangeRates.new.rate("USD", "JPY")
  end
end
  1) ExchangeRates blocks unstubbed requests
     Failure/Error: res = Net::HTTP.get_response(URI("#{@base_url}/latest?from=#{from}&to=#{to}"))

     WebMock::NetConnectNotAllowedError:
       Real HTTP connections are disabled. Unregistered request: GET https://rates.example.com/latest?from=USD&to=JPY with headers {'Accept'=>'*/*', ...}

       You can stub this request with the following snippet:

       stub_request(:get, "https://rates.example.com/latest?from=USD&to=JPY").
       ...

4 examples, 1 failure

The advantage over a double is that your real HTTP code (URL building, status handling, JSON parsing) is exercised too. For Minitest, require "webmock/minitest". The vcr gem builds on WebMock: it records real responses once and replays them afterwards. See Testing in CI for keeping tests off the network.

Other libraries

Tips

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents