Skip to content
Tutorials Center
My learning

Topics

Lesson 103 of 134 ยท Testing and Tooling

Test Doubles

Learn how to isolate Ruby tests with fakes, stubs, spies and mocks. Use dependency injection, write your own doubles and stub methods safely with Minitest.

Real programs talk to things that are slow, unreliable or dangerous in a test: a payment service, an email server, the clock, a random number generator, a database. You do not want a test suite that charges a real credit card, sends real emails or fails at midnight. The solution is a test double: an object that stands in for the real collaborator during a test, the way a stunt double stands in for an actor.

This lesson explains the four common kinds of doubles (fakes, stubs, spies and mocks), shows the design habit that makes doubles easy (dependency injection), and builds each double by hand with plain Ruby and Minitest. Writing them yourself is the best way to understand what the helper libraries do.

Minitest 6 (the version in Ruby 4.0) no longer includes Minitest::Mock or Object#stub. They moved to a separate gem called minitest-mock. Our runner cannot install gems, and require "minitest/mock" raises LoadError: cannot load such file -- minitest/mock. This is a good reason to learn the hand-written techniques below: they work everywhere, with no gem at all. The gem version is shown in a read-only snippet near the end.

The problem: a hard-wired collaborator

Here is a Checkout class that creates its own payment gateway inside a method. This looks innocent, but it cannot be tested without calling the real thing. In this sandbox the "real" gateway tries to open a network connection to a payment server.

Ruby A test that reaches the real gateway (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The test errors with Errno::ECONNREFUSED: Connection refused - connect(2) for "127.0.0.1" port 9 from the socket call, a problem that has nothing to do with our logic. On a developer laptop it might even succeed and charge a card. Either way the test is slow, flaky and unsafe. The root cause is in the design: Checkout chooses its own collaborator.

Dependency injection: let the caller choose

The fix is simple. Let Checkout receive the gateway instead of creating it, usually as a constructor argument with the real one as the default. In production nobody changes anything, and in a test you hand in a double.

Ruby
class Checkout
  def initialize(gateway: CardGateway.new)
    @gateway = gateway
  end

  def pay(cents)
    @gateway.charge(cents)
  end
end

This is the single most useful trick in testable Ruby. It is also not "extra ceremony" (as it is sometimes in other languages): Ruby's duck typing means the double only needs the methods that Checkout calls, not a shared interface or base class. See Duck Typing and Polymorphism and Design Principles in Ruby.

Four kinds of doubles

Kind What it does Checks the test...
Dummy Fills a parameter that is never used nothing
Stub Returns canned answers the result your code computes from them
Fake A simplified but working implementation (an in-memory store) the final state or result
Spy Records how it was called, and you inspect that afterwards the calls that were made
Mock Knows in advance which calls to expect and verifies them that the expected calls happened

The lines blur in practice, and many people say "mock" for all of them. What matters is the question each answers: what comes back? (stub), what ended up stored? (fake), what was called? (spy, mock).

Stub: a canned answer

A stub is as small as an object with one method. It lets you test how your code reacts to a particular answer, including failures that are hard to trigger for real.

Ruby Stub and spy gateways with injection

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

ApprovingGateway and DecliningGateway are stubs: each returns one canned answer, and that is how we reach the declined path without a real card. SpyGateway records what it receives, and the tests ask it afterwards. The last test checks something negative, that the gateway was not called at all, which is hard to see without a spy. Real code can have a very long list of such edge cases, and with doubles each runs in microseconds.

Fake: a simple working replacement

A fake has real behavior, just a simpler version. The classic example is an in-memory repository standing in for a database. Because it behaves like the real thing, tests can check the final state instead of the individual calls, which makes them less brittle.

Ruby An in-memory fake repository

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The tests never mention which methods of the repository Signup called. They only check the outcome (one user stored, no duplicate). If we later change Signup to call a different repository method, these tests still pass, as long as behavior is the same.

Prefer a fake when the collaborator has state and several related methods (a store, a queue, a cache). Prefer a stub or spy for a single call such as "send this email" or "charge this card".

Stubbing a method on an existing object

Dependency injection is not always possible. Sometimes the code you test calls a global like Time.now, rand or File.read. For those you replace a method temporarily, only for the duration of one block, and always restore it afterwards. Ruby's singleton methods make this a dozen lines. The helper below is a small version of what minitest-mock provides as stub.

Ruby A hand-written with_stub helper

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The important part is the ensure block: whatever happens inside the test, the original method is put back. Without it, one failing test could leave Time.now broken for every test that runs after it, which is a nightmare to debug. Notice also that we stubbed with a fixed Time and checked three different hours. That turns "depends on when you run it" into a deterministic test.

Stubbing global methods is a last resort. It couples the test to how the code is written (that it calls Time.now), and forgetting to restore breaks other tests. The cleaner design is to inject the clock: Greeter.new(clock: -> { Time.now }), then pass -> { fake_time } in the test. Use method stubbing for code you cannot change.

Mocks: expectations that are verified

A mock is set up before the action with the calls it should receive, and it can verify afterwards that all of them happened with the right arguments. That is a stricter spy. Here is a tiny hand-written mock, so you can see there is no magic:

Ruby A hand-written mock with verify

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

method_missing catches any method name, compares it with the next expected call, and returns the canned result; verify complains if expected calls are still waiting. This is how every mocking library works at its core (the real ones also support ordering rules, keyword arguments and nicer messages). The technique itself is explained in method_missing and respond_to_missing?.

For reference, this is how the same checks look with the minitest-mock gem. It is a read-only example, because the gem is not available here:

Ruby
require "minitest/autorun"
require "minitest/mock"      # gem "minitest-mock" in your Gemfile (Minitest 6)

class MailerTest < Minitest::Test
  def test_welcome
    smtp = Minitest::Mock.new
    smtp.expect(:deliver, true, ["[email protected]", "Welcome!"])

    Mailer.new(smtp: smtp).welcome("[email protected]")

    smtp.verify
  end

  def test_with_stub
    Time.stub(:now, Time.new(2030, 1, 1, 9)) do
      assert_equal "Good morning", Greeter.new.greeting
    end
  end
end

If you use RSpec instead, instance_double, allow(...).to receive and expect(...).to have_received do the same jobs. See RSpec Overview.

Keeping doubles honest

A double is a claim about how the real object behaves. If the real CardGateway#charge is renamed or starts returning :declined as a symbol-in-a-hash, your stub keeps saying the old thing, and all tests stay green while production breaks. A few habits keep this under control.

  • Mock only what you own. Wrap third-party libraries in a small class of your own (CardGateway), and double that wrapper, not the library's internals.
  • Test the real thing too. Have at least one slower integration test that uses the real collaborator, or run the same contract tests against both the fake and the real class.
  • Prefer state over interaction. Asserting on results (fakes, return values) survives refactoring; asserting on every call (mocks) breaks whenever the implementation changes shape.
  • Keep doubles tiny. If setting up a double takes more lines than the code under test, the code under test probably has too many dependencies. That is the design telling you something.
  • Do not double value objects. A Money or Point is cheap and fast; use the real one.

Common mistakes

  • Mocking everything. A test where every collaborator is a mock only proves the mocks were called as you scripted.
  • Forgetting to restore a stubbed method. Always use ensure, or a block-based helper.
  • Verifying private details. Asserting that Checkout calls charge once is useful; asserting the exact order of five internal calls is brittle.
  • Skipping verify. A mock that is never verified checks nothing about missing calls.
  • Stubbing the object under test. Replacing a method of the very class you are testing makes the test meaningless.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the main benefit of passing a collaborator into a class (dependency injection)?

    When the caller chooses the collaborator, production code passes the real one and tests pass a stub, fake or spy.
  2. 2. Which double would you use to check that a method was never called?

    A spy records every call, so a test can assert that its list of calls is empty. A stub only returns canned answers.
  3. 3. Why does the with_stub helper restore the original method inside an ensure block?

    ensure always runs. Without it, a failing test could leave Time.now replaced for all later tests.
  4. 4. What happened to Minitest::Mock and Object#stub in Minitest 6 (Ruby 4.0)?

    require "minitest/mock" raises LoadError unless the minitest-mock gem is installed, so add it to your Gemfile or use hand-written doubles.
  5. 5. Which is the best use of a fake rather than a stub?

    A fake has real, simplified behavior and state, so tests can check outcomes instead of individual calls.

Summary

  • A test double replaces a slow, random or risky collaborator so tests stay fast, deterministic and safe.
  • Dependency injection (a constructor argument with a real default) makes doubles easy, and duck typing means a double needs only the methods that get called.
  • Stubs return canned answers, fakes are simplified working versions, spies record calls, and mocks verify expected calls.
  • To replace a method on an existing object or class, redefine it in a block and restore it in ensure; inject a clock instead of stubbing Time.now when you can.
  • Minitest 6 moved Minitest::Mock and stub into the minitest-mock gem; hand-written doubles need no gem.
  • Keep doubles honest: double only what you own, prefer state over interactions, and keep a few tests with the real collaborator.

Next: Debugging Ruby