Mocking
A test double replaces a real collaborator so a test can control one thing at a time. Used well, it isolates behaviour and makes slow or nondeterministic dependencies instant. Used badly, it replaces the thing you were trying to verify and produces a suite that passes while the product is broken.
The 60-second answer
Section titled “The 60-second answer”“A stub returns canned answers, a mock also asserts that it was called, a spy records calls so you can assert afterwards, and a fake is a lightweight working implementation. The rule is to mock at the boundary of your system — third-party APIs, email, payments, clock, randomness — and use real objects inside it. Mocking your own classes couples tests to implementation and breaks on every refactor. The real question is always whether the thing you replaced is the thing you were trying to test; if it is, you have proved nothing.”
The vocabulary
Section titled “The vocabulary”| Term | What it does | Assertion style |
|---|---|---|
| Dummy | Placeholder passed but never used | None |
| Stub | Returns a canned value | Assert on the result |
| Mock | Stub that also expects a call | expect(...).to receive(...) before |
| Spy | Records calls, real or stubbed | Assert afterwards |
| Fake | Working in-memory implementation | Assert on state |
The word “mock” is used loosely for all of these, which is why arguments about mocking are often arguments about definitions. In an interview, say which behaviour you want: “I need it to return this value” (stub) versus “I need to know it was called with these arguments” (mock or spy).
Mocking at the boundary
Section titled “Mocking at the boundary”RSpec.describe ChargeCustomer do it "charges the saved card and marks the invoice paid" do gateway = instance_double(PaymentGateway, charge: Gateway::Result.new(success: true)) invoice = create(:invoice, :with_saved_card)
described_class.new(gateway:).call(invoice)
expect(invoice.reload).to be_paid endendThe gateway is a real external system, so it is doubled. The invoice is a real record, so the test
proves the state change. instance_double verifies that charge exists on the class, so a rename
breaks the test loudly instead of silently passing.
Behind a double: network calls (payments, geocoding, LLM APIs), email and SMS, the clock
(travel_to), randomness, filesystem and object storage, and authentication in request specs where
the real code path is expensive. Stay real: your own domain objects, the database in integration
tests, and serialisers and validators — exactly where contract bugs live.
Mocking your own code is the smell
Section titled “Mocking your own code is the smell”# Brittle: asserts the call, not the outcome — and passes whatever the real rule does.expect(TaxCalculator).to receive(:new).with(order).and_return(double(calculate: 12))expect(Invoice.new(order).total).to eq(112)
# Better: use the real calculator, which is pure and fast.expect(Invoice.new(order).total).to eq(108)- It encodes the implementation. Renaming a method fails the test although behaviour is unchanged.
- It cannot catch integration bugs. Both sides pass with mismatched arguments.
- It makes refactoring expensive, which is exactly when you need tests most.
The legitimate exception: mocking your own slow, separately tested collaborator inside a controller spec — stubbing an email service whose behaviour has its own tests.
Stubs can lie
Section titled “Stubs can lie”Ruby’s and_return enforces neither arity nor return types. Two guards help: instance_double and
class_double verify method existence, and verify_partial_doubles = true (the rspec-rails default)
makes stubbing a non-existent method on a real object raise instead of silently passing.
allow(Time).to receive(:now).and_return(Time.utc(2026, 1, 1))# Prefer travel_to(Time.utc(2026, 1, 1)) — it restores state and reads better.Interactions versus state
Section titled “Interactions versus state”- State verification — call the code, assert on observable output or persisted state. Refactor tolerant, catches real bugs.
- Interaction verification — assert a collaborator received a message. Necessary for fire-and- forget side effects, brittle everywhere else.
Use interaction verification only when the effect is the message and there is no state to observe:
expect { described_class.call(user) }.to have_enqueued_job(WelcomeEmailJob).with(user)Fakes and contracts
Section titled “Fakes and contracts”A fake is an in-memory implementation of an interface: a repository, an HTTP server, a clock. Fakes beat stubs for anything with non-trivial behaviour, because they behave, and they are shared once instead of restubbed per test. The risk is divergence, so guard it with a contract test: run the same expectations against the fake and the real adapter.
[InMemoryRepository, SequelRepository].each do |repo_class| RSpec.describe "Repository contract: #{repo_class}" do it "finds a saved record by id" do repo = repo_class.new expect(repo.find(repo.save(Entity.new(id: "1")).id)).to be_present end endendAvoiding brittle tests
Section titled “Avoiding brittle tests”- Assert on outcomes. What came out, what changed in the world?
- Mock one layer deep. Stubbing a collaborator that stubs two more is testing fiction.
- Use verified doubles.
instance_double,class_double,verify_partial_doubles. - Do not assert call order unless order is a requirement.
- Do not assert exact arguments when one field matters; use
hash_including. - Keep doubles local. A stub in a global
beforehides from the reader.
Follow-up questions
Section titled “Follow-up questions”- Stub versus mock versus spy — one sentence each.
- When is it acceptable to mock one of your own classes?
- How do you mock the clock without leaking state between tests?
- What is a contract test and why does a fake need one?
Common traps
Section titled “Common traps”- Mocking the thing under test. The test proves the mock works.
- Stubbing a method that does not exist. Verified doubles catch it; plain
doubledoes not. - Asserting call order by default. It makes every refactor a failure.
- Global stubs in
before(:all). They leak and produce order-dependent failures. - Faking the database in an integration test. You lose the layer the test exists for.