Test driven development in Rails: Minitest, RSpec and a real workflow, step by step
TL;DR
Difficulty: Intermediate
Minitest or RSpec is a dialect. Fixtures or factories is the decision that costs.
- Start a new Rails application on Minitest unless the team already writes RSpec well; keep a healthy RSpec suite.
- Fixtures for the world every test assumes, explicit records in the test for the rule it checks. Factories when a model needs many variations.
- Predict every red before you run it. A test that passes at once proves nothing until you know why.
- Test each rule at the lowest level that can see it: plain Ruby for a price, a model test for an overlap, a request test for the status and message.
- Freeze the clock with travel_to, block real HTTP with WebMock, and let Rails run the suite in parallel, knowing the fixed part sets a ceiling.
Most TDD tutorials stop at a calculator. This one takes two real rules from an invented chain of bicycle workshops, a booking that must not overlap and a repair price with VAT, and builds them test first in Rails 7.1, with the test, the prediction and the code at every step. Along the way it settles Minitest or RSpec, and the more important question of where your test data comes from.
The question behind this chapter
"How do I actually do test driven development in Rails, step by step, and should I use Minitest or RSpec?"
Most answers to that question stop at a toy: a Calculator class, one test, one method, done. The hard part of test driven development (TDD) in a real Rails application is everything around that toy. Which kind of test do you write for a business rule? Where does the test data come from? What do you do about the clock, the email, the supplier's API? And how do you keep the whole thing fast enough that you actually run it every few minutes?
This chapter answers those questions on a real feature, step by step, with the test and the code at every step. It is written for Rails 7.1 (7.1.3.3 is the current patch release, from 16 May 2024) on Ruby 3.3, with the library versions current on 28 May 2024: Minitest 5.23, rspec rails 6.1.2, factory_bot_rails 6.4.3, WebMock 3.23 and VCR 6.2123.
It builds on the testing map for web applications, which explains what TDD, behaviour driven development (BDD) and end to end tests are and how much of each a web application needs. This chapter goes one level down, into Rails. The data model comes from Active Record done well, and the first tests and the double booking constraint from starting a new Rails application.
The example runs through the whole chapter. Cogwell Cycles is an invented chain of six bicycle repair workshops in Sheffield (cogwellcycles.example), founded by Hannah. It has 38 mechanics, about 1,150 repair bookings a week and 9,000 active customers. Its two developers, Priya and Owen, are building their own Rails application to replace spreadsheets and a rented booking widget. The company and the people are made up. The code is real.
For the record, this is how I work myself: I build web applications on Ruby on Rails, and I write the tests first. Behaviour driven development with Cucumber sits on top, and it gets its own chapter next week.
Three rules for the whole chapter
The Rails testing guide explains every tool in this chapter well4. What it cannot give you is a way to decide between them. These three rules do that job here, and each one is earned in its own section below.
- The dialect and the data. "Minitest or RSpec" looks like the big decision and is the small one. It is a dialect: two ways of saying the same thing, which can even live side by side in one application. "Fixtures or factories" looks like a detail and is the big one. It decides how fast your suite runs, how stable it is, and whether a reader can see why a test passes.
- Predict the red. Before you run a new test, say out loud, or write in a comment, exactly how it will fail. If it fails differently, or passes, stop: you have learned something about your code or your test, and both are worth knowing before you write another line.
- Test at the lowest level that can see the rule. A price calculation needs no database. An overlap rule needs the database but no HTTP. A status code needs a request but no browser. Every level you climb costs time on every run, so climb only as far as the rule forces you to.
None of these is in the official guide in this form. They are my distillation, and the reasoning is shown so you can disagree with it on evidence.
Test driven development in one minute, from the source
Kent Beck described the practice in "Test Driven Development: By Example" in 20025. The loop has three steps:
- Red. Write a small test for behaviour that does not exist yet. Run it and watch it fail.
- Green. Write the least code that makes it pass. Quick and plain is fine here.
- Refactor. With the test green, clean up the code and the test. Run again after every change.
Martin Fowler's summary, updated in December 2023, adds the step that people forget: before the loop starts, write a list of the test cases you expect to need, then pick one, go round the loop, and pick the next. New cases go on the list as you think of them6.
That list is where the design happens. Writing it forces you to say what the feature is before you say how it works.
Example: the test list for the booking rule
Hannah's rule is simple to say: a mechanic cannot be booked for two repairs at the same time. Priya writes the test list before any code, in plain words:
- A booking that starts while another one runs, for the same mechanic, is refused.
- Back to back bookings are fine: one ends at 10am, the next starts at 10am.
- A different mechanic at the same time is fine.
- A cancelled booking does not block the slot.
- Moving an existing booking by 15 minutes does not clash with itself.
- Two requests at the same moment cannot both win.
Six lines, and already two decisions have been made that were never written down before: the end time is exclusive (case 2), and cancelling frees the slot (case 4). Hannah confirms both in a two minute conversation. No design review costs less.
Minitest: what Rails gives you on day one
Rails ships with Minitest as its default testing library and builds on it with its own test classes4. Minitest itself is written by Ryan Davis, and its README describes it as a small and fast unit testing framework, with an optional spec style on top7.
When you run rails new, Rails 7.1 writes a test folder and a test/test_helper.rb. The generated helper is short, and every line matters8. Here it is:
# test/test_helper.rb, as generated by Rails 7.1
ENV["RAILS_ENV"] ||= "test"
require_relative "../config/environment"
require "rails/test_help"
module ActiveSupport
class TestCase
# Run tests in parallel with specified workers
parallelize(workers: :number_of_processors)
# Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
fixtures :all
end
end
Three defaults are hiding in there. Tests run in parallel, one process per CPU core. All fixtures are loaded. And every test runs inside a database transaction that is rolled back at the end, so no test sees another test's data49. A fourth default lives in Minitest itself: tests run in random order, every time, unless you explicitly opt out7.
A Minitest test in Rails is a Ruby class. Each test "..." do block becomes a method, and assertions such as assert_equal, assert_not and assert_includes check the result. You run the suite with bin/rails test, one file with bin/rails test test/models/booking_test.rb, and one test by adding its line number: bin/rails test test/models/booking_test.rb:144.
RSpec: the alternative, from its own documentation
RSpec began in 2005 as an experiment by Steven Baker10, in the same years in which Dan North was describing behaviour driven development11. That lineage still shows. The rspec rails README calls itself a drop in alternative to Minitest and describes its tests as specifications of how the application should behave, "expressed in plain English"3.
You add the rspec-rails gem, run bin/rails generate rspec:install, and write files under spec/. Version 6.x supports Rails 6.1 and 7.x3. Tests are grouped in describe and context blocks, each example is an it block, and expectations read like sentences: expect(booking).not_to be_valid. let defines lazily built helpers, and rspec mocks offers verifying doubles, which fail if you stub a method the real class does not have12.
Two defaults differ from Minitest. The generated spec_helper.rb contains config.order = :random, but inside a commented out block, so random order is something you switch on13. And RSpec does not use Rails' built in parallel testing. Teams that want it reach for a separate gem, usually parallel_tests (4.7.1 at the time of writing), which runs several RSpec processes, each with its own test database14.
The culture around each
Both communities are large and serious, and it is worth knowing where each comes from. RSpec grew out of the BDD movement and from the start emphasised describing behaviour in readable language. Minitest is the choice of the Rails core team: the Rails Guides use it on every page4, and David Heinemeier Hansson, who created Rails, wrote in 2014 that strict test first rhetoric had become dogma, while defending testing itself15. RSpec is very widely used in Rails companies: in Planet Argon's 2022 Rails community survey it appears among both the most loved and the most frustrating gems, which is roughly what popularity looks like16.
Example: the same first test in both dialects
Here is case 1 from Priya's list, first in Minitest:
# test/models/booking_test.rb
require "test_helper"
class BookingTest < ActiveSupport::TestCase
test "a booking that starts while another runs for the same mechanic is refused" do
nine = Time.zone.parse("2024-06-08 09:00") # a Saturday
Booking.create!(mechanic: mechanics(:sam), customer: customers(:alex),
starts_at: nine, ends_at: nine + 1.hour)
clash = Booking.new(mechanic: mechanics(:sam), customer: customers(:alex),
starts_at: nine + 30.minutes, ends_at: nine + 90.minutes)
assert_not clash.valid?
assert_includes clash.errors[:starts_at], "overlaps another booking for this mechanic"
end
end
And the same in RSpec, with factory_bot for the data:
# spec/models/booking_spec.rb
require "rails_helper"
RSpec.describe Booking do
let(:sam) { create(:mechanic) }
let(:nine) { Time.zone.parse("2024-06-08 09:00") }
it "is refused when it starts while another booking runs for the same mechanic" do
create(:booking, mechanic: sam, starts_at: nine, ends_at: nine + 1.hour)
clash = build(:booking, mechanic: sam, starts_at: nine + 30.minutes, ends_at: nine + 90.minutes)
expect(clash).not_to be_valid
expect(clash.errors[:starts_at]).to include("overlaps another booking for this mechanic")
end
end
Read them side by side. The rule, the data and the check are the same. What differs is vocabulary: test against it, assert_not against expect(...).not_to, and fixtures (mechanics(:sam)) against factories (create(:mechanic)). The first two differences are the dialect. The third is the data decision, and it matters more than the other two combined.
Minitest or RSpec, side by side
This table is drawn from each project's own documentation347121314.
| Question | Minitest in Rails | RSpec through rspec rails |
|---|---|---|
| Comes with Rails | Yes, the default, and generators write its tests | A gem, set up with rails generate rspec:install |
| Style | Ruby classes and methods, assert_equal | describe, context, it, expect(...).to |
| Vocabulary to learn | Small: Ruby plus a few dozen assertions | Larger: let, subject, hooks, matchers, shared examples |
| Where the examples live | Every page of the Rails Guides | rspec.info and the rspec rails README |
| Test data by default | Fixtures, all loaded | Fixtures supported, most teams add factory_bot |
| Random order | On by default | Opt in, commented out in the generated config |
| Parallel runs | Built in since Rails 6, parallelize | Not built in, parallel_tests gem |
| Test doubles | minitest/mock, deliberately small | rspec mocks with verifying doubles |
| Run one test | bin/rails test path:line | bundle exec rspec path:line |
| Find the slowest tests | bin/rails test --profile | rspec --profile |
My view
For a new Rails application, start with Minitest unless the team already writes RSpec fluently. The reasons are practical, not tribal. Every example in the Rails Guides works as written, the generators write the tests for you, parallel testing needs one line, and a newcomer has less vocabulary to learn before writing a useful test. Owen at Cogwell comes from Jest, whose describe and it look like RSpec, and he still found Minitest readable within a day, because it is just Ruby.
If you already have a healthy RSpec suite, keep it. Rewriting tests into another dialect buys you nothing a customer would notice, and good RSpec suites are as fast and as trustworthy as good Minitest suites. The speed of a Rails suite almost never comes down to the test library. It comes down to data, boot time and browser tests, and those are the same in both. That is my judgement, not a benchmark, and the next section shows where the time actually goes.
Fixtures or factories: the decision that actually costs
Test data is the part of a test that is not the rule. It is also where most of the cost of a Rails suite hides. There are two standard approaches.
Fixtures are Rails' built in answer. They are YAML files (a plain text format for structured data), one per table, under test/fixtures. The Rails guide calls them "a fancy word for sample data"4. At the start of a run, Rails deletes the rows in each fixture table and inserts the fixture rows, once. Every test then runs inside a transaction that is rolled back, so the fixtures are back in their original state for the next test without being inserted again49. Each fixture has a label, and Rails derives a stable id from it, so you can refer to mechanic: sam instead of mechanic_id: 19. Fixture rows are inserted directly into the tables, not saved through your models, so validations and callbacks do not run on them. The guide itself advises using fixtures only for default data that suits the common case, not for every object a test needs4.
Factories come from factory_bot, maintained by thoughtbot. A factory is a recipe for a valid object, with defaults you override per test. Its build strategies decide how much work happens: build returns an unsaved object, create saves it, attributes_for returns a hash, and build_stubbed returns an object that pretends to be saved without touching the database17. In current versions, associations follow the parent's strategy by default, so build(:booking) builds its mechanic instead of saving it18.
The trade off is easy to state once you see the two failure modes.
- Fixtures are fast and stable, but they are a shared world. A test that says
bookings(:saturday_service)does not show you what that booking contains. Gerard Meszaros named this problem the Mystery Guest in "xUnit Test Patterns" (2007): the reader cannot see the cause and effect between the data and the check, because the data lives somewhere else19. And because every test shares the same fixtures, changing one fixture to suit a new test can quietly break five others. - Factories put the data in the test, which is clear, but every
createwrites rows, and every row written runs validations, callbacks and a database round trip. A factory for a job card can quietly create a workshop, a mechanic, a customer and a booking first. Multiply that by every test, every run, and the suite slows down without anyone deciding it should.
My view: fixtures for the world, explicit records for the rule
At Cogwell, and in most Rails applications I would start today, the split is this. Fixtures hold the world that every test can assume: the six workshops, a handful of mechanics, a few customers, the common parts. Each test then creates, in the test itself and in plain sight, the few records that its rule is about. The world is loaded once and costs nearly nothing per test. The records that decide the outcome are visible on the page, so there is no Mystery Guest where it counts.
Factories earn their place when a model needs many valid variations that fixtures would turn into a zoo: invoices with every combination of discount, VAT treatment and payment state, say. Then a factory with traits is clearer than forty fixture rows. Use build or build_stubbed whenever the test does not need the database, and create only when it does.
Example: Cogwell's fixture world
# test/fixtures/workshops.yml
kelham:
name: Kelham Island
ecclesall:
name: Ecclesall Road
# test/fixtures/mechanics.yml
sam:
name: Sam
workshop: kelham
dev:
name: Dev
workshop: kelham
# test/fixtures/customers.yml
alex:
first_name: Alex
email: alex@cogwellcycles.example
mobile: "+447700900123"
Count what the overlap test above writes to the database. With fixtures, it writes one row: the first booking, created in the test where you can see it. The mechanic and the customer were loaded once at the start of the run. With the factory version, create(:mechanic) writes a workshop and a mechanic, and create(:booking) writes a customer and the booking: four rows before the first assertion. Neither number is large. The habit is what matters, because it repeats in every test you will ever write.
The same count for the other tests in this chapter tells the same story:
The request test writes nothing with fixtures because the booking it collides with is already in the fixture world. The factory version has to create that booking, its mechanic, the mechanic's workshop and a customer first. The price test writes nothing in either style, which is the strongest argument of all: the fastest row is the one a test never needs.
Which tests to write in Rails, and why request tests replaced controller tests
Rails gives you a test class for each layer4. Here is what each is for, using the rule of the lowest level that can see the rule.
| Test type | Base class | Folder | Use it for |
|---|---|---|---|
| Plain object and model | ActiveSupport::TestCase | test/models | Calculations, validations, scopes, constraints |
| Request (integration) | ActionDispatch::IntegrationTest | test/controllers or test/integration | Routing, params, status codes, redirects, the HTML or JSON returned |
| Mailer | ActionMailer::TestCase | test/mailers | Recipients, subject, the content of an email |
| Job | ActiveJob::TestCase | test/jobs | What a background job does when it runs |
| Helper | ActionView::TestCase | test/helpers | Small view helpers, such as formatting money |
| System | ApplicationSystemTestCase | test/system | A real browser, JavaScript, the whole journey |
The odd one out historically is the controller test. Older Rails applications tested controllers in isolation and checked which instance variables an action set (assigns) and which template it rendered (assert_template). Rails 5.0 removed both and moved them into a separate gem, rails controller testing20. In the same year the RSpec team wrote that the official recommendation of both the Rails team and the RSpec core team was to write request specs instead, because a request goes through the router, the middleware and a real response, which catches problems a controller test misses21.
Rails 7.1 follows that advice in its own generators. A scaffold still writes test/controllers/bookings_controller_test.rb, but the class inside inherits from ActionDispatch::IntegrationTest4. The folder kept its old name, and the test became a request test.
System tests drive a real browser and belong to the outermost loop. They are the subject of next week's chapter on BDD and end to end testing in Rails, so this chapter stops one level below them.
The walk through, part one: a booking cannot overlap
Now the real thing. Priya pairs with Owen on the booking rule, one case from the test list at a time. Before each run she writes down the failure she expects. The bookings table and its double booking constraint already exist from the first decisions chapter: the database refuses overlapping live bookings. What is missing is the validation that gives a person at the booking form a friendly message instead of an error page. In the language of the Active Record chapter, the constraint stops the twin and the validation serves the form.
First, a small helper inside the test class, so each test reads as one line of setup. It also freezes the clock, for a reason explained in the section on time below.
# test/models/booking_test.rb
require "test_helper"
class BookingTest < ActiveSupport::TestCase
setup do
travel_to Time.zone.parse("2024-06-07 18:00") # Friday evening, before the Saturday rush
end
def nine = Time.zone.parse("2024-06-08 09:00") # Saturday, 9am
# Builds an unsaved booking; the mechanic and customer come from fixtures
def booking(from:, minutes: 60, mechanic: mechanics(:sam), **attrs)
Booking.new(mechanic:, customer: customers(:alex),
starts_at: from, ends_at: from + minutes.minutes, **attrs)
end
end
Cycle 1: the overlap is refused
The test:
test "a booking that starts while another runs for the same mechanic is refused" do
booking(from: nine).save!
clash = booking(from: nine + 30.minutes)
assert_not clash.valid?
assert_includes clash.errors[:starts_at], "overlaps another booking for this mechanic"
end
The prediction, written before running: "assert_not fails, because valid? returns true. There is no validation yet." Then the run:
bin/rails test test/models/booking_test.rb
# Failure:
# BookingTest#test_a_booking_that_starts_while_another_runs_for_the_same_mechanic_is_refused
# Expected true to be nil or false
Red, and the red they predicted. Now the least code that passes. Beck's advice for this moment is to be shameless, and Priya is5:
# app/models/booking.rb
class Booking < ApplicationRecord
belongs_to :mechanic
belongs_to :customer
validate :mechanic_is_free
private
def mechanic_is_free
# Deliberately too simple: any other booking for this mechanic counts as a clash
if Booking.where(mechanic_id: mechanic_id).exists?
errors.add(:starts_at, "overlaps another booking for this mechanic")
end
end
end
Green. The code is wrong, and everybody at the desk knows it. That is the point: the next test on the list will prove it wrong, and the real logic will arrive because a test demanded it, not because someone guessed.
Cycle 2: back to back is fine
test "a booking may start the minute the previous one ends" do
booking(from: nine).save!
next_one = booking(from: nine + 1.hour)
assert next_one.valid?, next_one.errors.full_messages.to_sentence
end
Prediction: "Fails, with the overlap message, because the fake rule refuses any second booking." The run says Starts at overlaps another booking for this mechanic. Correct red. The second argument to assert is the message Minitest prints on failure, which is why the reason appears in the output.
Two time ranges overlap when each one starts before the other ends. With the end time exclusive, as Hannah confirmed, that is two strict comparisons:
def mechanic_is_free
clash = Booking.where(mechanic_id: mechanic_id)
.where("starts_at < ? AND ends_at > ?", ends_at, starts_at)
errors.add(:starts_at, "overlaps another booking for this mechanic") if clash.exists?
end
Both tests pass. Note that this is the same rule the database constraint uses: a PostgreSQL tsrange excludes its upper bound by default, so the database and the model now agree that 10am to 11am does not touch 9am to 10am22.
Cycle 3: a different mechanic, and a test that passes at once
test "another mechanic can be booked at the same time" do
booking(from: nine).save!
colleague = booking(from: nine, mechanic: mechanics(:dev))
assert colleague.valid?
end
Prediction: "This should pass already, because the query filters by mechanic_id." And it does. Here the rule "predict the red" earns its keep. A test that passes on its first run proves nothing until you know why. So Owen deletes .where(mechanic_id: mechanic_id) for a moment, runs the test, sees it fail, and puts the line back. Now the test is known to guard that line, and it stays as documentation of case 3. Thirty seconds, and the alternative is a test that might be checking nothing at all.
Cycle 4: cancelled bookings free the slot
test "a cancelled booking does not block the slot" do
booking(from: nine, cancelled_at: Time.current).save!
assert booking(from: nine).valid?
end
Prediction: "Fails with the overlap message, because cancelled rows are still counted." Correct. The fix is a scope that names the idea, which the rest of the application will want too:
scope :active, -> { where(cancelled_at: nil) }
def mechanic_is_free
clash = Booking.active.where(mechanic_id: mechanic_id)
.where("starts_at < ? AND ends_at > ?", ends_at, starts_at)
errors.add(:starts_at, "overlaps another booking for this mechanic") if clash.exists?
end
Cycle 5: moving a booking does not clash with itself
test "moving a booking by 15 minutes does not clash with itself" do
existing = booking(from: nine)
existing.save!
existing.starts_at += 15.minutes
existing.ends_at += 15.minutes
assert existing.valid?, existing.errors.full_messages.to_sentence
end
Prediction: "Fails, because the query finds the booking's own row in the database, still at 9am, and 9.15am to 10.15am overlaps it." Correct red. One more condition:
clash = Booking.active.where(mechanic_id: mechanic_id)
.where("starts_at < ? AND ends_at > ?", ends_at, starts_at)
.where.not(id: id)
For a new booking id is nil, and where.not(id: nil) becomes id IS NOT NULL, which every saved row satisfies. So one line serves both cases.
Refactor: say what the code means
All five tests are green. Now, and only now, Priya tidies up. The SQL fragment moves into a named scope, the validation skips half filled forms (the presence validations will report those), and cancelled bookings skip the check entirely:
# app/models/booking.rb
class Booking < ApplicationRecord
belongs_to :mechanic
belongs_to :customer
# the other associations, as in the Active Record chapter
validates :starts_at, :ends_at, presence: true
validate :mechanic_is_free
scope :active, -> { where(cancelled_at: nil) }
# Two ranges overlap when each starts before the other ends (end time exclusive)
scope :overlapping, ->(from, to) { where("starts_at < ? AND ends_at > ?", to, from) }
private
def mechanic_is_free
return if cancelled_at? || starts_at.blank? || ends_at.blank?
clash = Booking.active.where(mechanic_id: mechanic_id)
.overlapping(starts_at, ends_at)
.where.not(id: id)
errors.add(:starts_at, "overlaps another booking for this mechanic") if clash.exists?
end
end
bin/rails test test/models/booking_test.rb again: five runs, all green. The refactor changed the shape of the code and not a single behaviour, and the tests are what prove it.
Cycle 6: the twin, pinned in the database
The last case on the list, two requests at the same moment, cannot be solved by a validation. Both requests check, both see a free slot, both save. Only the database can stop that, and the constraint from the first decisions chapter does. The test for it already exists there: it saves a clashing booking and expects ActiveRecord::StatementInvalid naming bookings_no_double_booking. With the validation in place that test would now stop at the validation, so it changes one word, save! becomes save!(validate: false), to go straight to the database the way a twin request would.
Priya found that out the way TDD intends. After cycle 1 she ran the whole suite, not only the new file, and the old constraint test turned red: save! now raised ActiveRecord::RecordInvalid from the new validation, before the database was ever asked. The fix is one argument. The lesson is that the loop does two jobs. It guards the new code, and it tells you when an old test has quietly started testing something else.
The walk through, part two: the price of a repair
The second feature is the price on a job card: labour plus parts plus VAT. By the lowest level rule, this needs no database at all, so it becomes a plain Ruby object in app/models, which Rails autoloads like any model. Its test inherits from ActiveSupport::TestCase but never touches a table, so it runs in a fraction of a millisecond.
Money is in whole pence, as decided in Active Record done well. Cogwell's labour rate is £45 an hour, and the UK standard rate of VAT is 20%23. Hannah's accountant wants VAT worked out on the job's net total and rounded to the nearest penny, halves rounded up. That rounding rule is the accountant's choice for Cogwell. Check yours with your own accountant: this chapter is general information, not tax advice.
The test list, written first:
- Labour: 90 minutes at £45 an hour is £67.50.
- Parts are added: a chain at £12.50 and a brake cable at £5.00 make a net total of £85.00.
- VAT at 20% on £85.00 is £17.00, so the total is £102.00.
- VAT that does not come to whole pence is rounded: 30 minutes plus an inner tube at £6.49.
- Labour that does not come to whole pence is rounded too.
Cycles 1 to 3: the straight path
The three tests:
# test/models/repair_price_test.rb
require "test_helper"
class RepairPriceTest < ActiveSupport::TestCase
RATE = 4_500 # £45.00 an hour, in pence
test "labour is charged by the minute" do
price = RepairPrice.new(minutes: 90, labour_rate_pence: RATE, vat_percent: 20)
assert_equal 6_750, price.labour_pence
end
test "parts are added to labour for the net total" do
price = RepairPrice.new(minutes: 90, labour_rate_pence: RATE,
parts_pence: [1_250, 500], vat_percent: 20)
assert_equal 8_500, price.net_pence
end
test "VAT is added to the net total" do
price = RepairPrice.new(minutes: 90, labour_rate_pence: RATE,
parts_pence: [1_250, 500], vat_percent: 20)
assert_equal 1_700, price.vat_pence
assert_equal 10_200, price.total_pence
end
end
Each was written and run alone, red first. The first red was NameError: uninitialized constant RepairPriceTest::RepairPrice, which is exactly the prediction for a class that does not exist yet. The code that made all three green is the obvious arithmetic:
# app/models/repair_price.rb (after cycle 3)
class RepairPrice
attr_reader :labour_pence, :parts_pence, :net_pence, :vat_pence, :total_pence
def initialize(minutes:, labour_rate_pence:, parts_pence: [], vat_percent:)
@labour_pence = labour_rate_pence * minutes / 60
@parts_pence = parts_pence.sum
@net_pence = @labour_pence + @parts_pence
@vat_pence = @net_pence * vat_percent / 100
@total_pence = @net_pence + @vat_pence
end
end
The numbers match Cogwell's average repair: £85 net, £102 with VAT.
Cycle 4: the penny that integer division loses
test "VAT is rounded to the nearest penny, halves up" do
# 30 minutes (£22.50) plus an inner tube (£6.49) is £28.99 net.
# 20% of 2,899 pence is 579.8 pence, which rounds to 580.
price = RepairPrice.new(minutes: 30, labour_rate_pence: RATE,
parts_pence: [649], vat_percent: 20)
assert_equal 580, price.vat_pence
assert_equal 3_479, price.total_pence
end
Prediction: "Fails with 579, because Ruby's integer division throws the fraction away." The run:
# Failure:
# RepairPriceTest#test_VAT_is_rounded_to_the_nearest_penny,_halves_up
# Expected: 580
# Actual: 579
This is the most valuable red in the chapter. The code from cycle 3 passed every test so far and would have undercharged VAT by up to a penny on most invoices, silently, for years. The fix is to calculate with exact fractions and round once, at the end. Ruby's Rational keeps the exact value, and round(half: :up) turns it into whole pence24. The new line:
@vat_pence = (@net_pence * vat_percent / 100r).round(half: :up)
The r suffix makes 100r a rational number, so the division is exact. Never use a float here: floats cannot represent most decimal fractions exactly, which is a bad property for money.
Cycle 5: labour that does not divide evenly
At £45 an hour, every whole minute costs exactly 75p, so today the labour line never needs rounding. A rate that does not divide by 60 would. The test uses a different rate on purpose, because the rule is "any rate", not "today's rate":
test "labour is rounded to the nearest penny when the rate does not divide evenly" do
# £46.00 an hour for 10 minutes is 766.67 pence
price = RepairPrice.new(minutes: 10, labour_rate_pence: 4_600, vat_percent: 20)
assert_equal 767, price.labour_pence
end
Prediction: "766, the same truncation." Correct. Now refactor, with one rounding rule named once:
# app/models/repair_price.rb (after the refactor)
class RepairPrice
attr_reader :labour_pence, :parts_pence, :net_pence, :vat_pence, :total_pence
def initialize(minutes:, labour_rate_pence:, parts_pence: [], vat_percent:)
@labour_pence = whole_pence(labour_rate_pence * minutes / 60r)
@parts_pence = parts_pence.sum
@net_pence = @labour_pence + @parts_pence
@vat_pence = whole_pence(@net_pence * vat_percent / 100r)
@total_pence = @net_pence + @vat_pence
end
private
# Exact fraction in, whole pence out, halves rounded up
def whole_pence(amount) = amount.round(half: :up)
end
Five tests, five green, and the whole file runs in well under a second because no test touches the database.
The walk through, part three: request, mailer, job and helper tests
The rules are proven at the lowest level. The levels above check only what they alone can see.
Example: the request test for the booking form
What a request test can see, and a model test cannot, is the HTTP conversation: the form posts, nothing is saved, the status says the input was rejected, and the message reaches the page.
# test/controllers/bookings_controller_test.rb
require "test_helper"
class BookingsControllerTest < ActionDispatch::IntegrationTest
setup { travel_to Time.zone.parse("2024-02-09 18:00") } # the evening before the fixture booking
test "an overlapping booking is refused with a message" do
taken = bookings(:saturday_service)
assert_no_difference("Booking.count") do
post bookings_url, params: { booking: {
mechanic_id: taken.mechanic_id, customer_id: taken.customer_id,
starts_at: taken.starts_at + 30.minutes, ends_at: taken.ends_at + 30.minutes } }
end
assert_response :unprocessable_entity
assert_match "overlaps another booking for this mechanic", response.body
end
end
Notice what this test does not do. It does not repeat cases 2 to 5. Those live in the model test, where they run faster and fail more precisely. One request test per outcome is enough: refused, and accepted.
In RSpec the same test is a request spec, the form the RSpec team recommends21:
# spec/requests/bookings_spec.rb
require "rails_helper"
RSpec.describe "Bookings", type: :request do
it "refuses an overlapping booking with a message" do
taken = create(:booking)
expect {
post bookings_path, params: { booking: {
mechanic_id: taken.mechanic_id, customer_id: taken.customer_id,
starts_at: taken.starts_at + 30.minutes, ends_at: taken.ends_at + 30.minutes } }
}.not_to change(Booking, :count)
expect(response).to have_http_status(:unprocessable_entity)
expect(response.body).to include("overlaps another booking for this mechanic")
end
end
Example: the mailer and the job
The "your bike is ready" email and its background job were built in the chapter on background jobs, email and files, including a job test that proves the email is sent once however often the job runs. Two tests complete the picture. The mailer test checks the email itself:
# test/mailers/ready_mailer_test.rb
require "test_helper"
class ReadyMailerTest < ActionMailer::TestCase
test "the ready email goes to the customer and names the workshop" do
card = job_cards(:kelham_puncture)
email = ReadyMailer.with(job_card: card).bike_ready
assert_emails(1) { email.deliver_now }
assert_equal [card.customer.email], email.to
assert_match "Kelham Island", email.subject
end
end
And a request test checks that moving a card to "ready" on the workshop board queues the job, without running it. Integration tests in Rails 7.1 include the Active Job test helpers automatically, so assert_enqueued_with is available without any setup25. The test:
test "marking a job card ready queues the ready email" do
sign_in_as users(:kelham_mechanic) # helper from the security chapter
card = job_cards(:kelham_puncture)
assert_enqueued_with(job: ReadyEmailJob, args: [card]) do
patch job_card_path(card), params: { job_card: { status: "ready" } }
end
end
The sign_in_as helper comes from the chapter on authentication, authorisation and security. Delivery settings for development, staging and production, so that test emails never reach a real customer, are covered in the article on safe transactional email with Postmark in Rails.
Example: a helper test for money on the page
Pence are right for arithmetic and wrong for people. A small helper formats them, and a helper test pins the format:
# app/helpers/application_helper.rb
module ApplicationHelper
def money(pence)
number_to_currency(pence / 100.0, unit: "£")
end
end
# test/helpers/application_helper_test.rb
require "test_helper"
class ApplicationHelperTest < ActionView::TestCase
test "money shows pounds with two decimal places" do
assert_equal "£102.00", money(10_200)
assert_equal "£34.79", money(3_479)
end
end
The float in the helper is fine. It only formats a value for display, after the exact arithmetic is done.
Time, and the outside world
Two things make tests lie: a clock that keeps moving, and a network you do not control.
Freezing the clock with travel_to
Rails includes time helpers in every test case. travel_to stubs Time.now, Date.today and DateTime.now so that the current time is the one you give it, and removes the stubs at the end of the test. freeze_time stops the clock at the current moment. By default travel_to also drops the microseconds, to avoid rounding differences with some databases, and Rails 7.1 lets you keep them with with_usec: true26.
This is why the booking tests above start with travel_to in setup. Without it, they contain a time bomb.
Example: the time bomb in the booking tests
Hannah asks for one more rule: a booking cannot start in the past. Priya writes the test first:
test "a booking cannot start in the past" do
travel_to Time.zone.parse("2024-06-08 09:30") # Saturday, half past nine
assert_not booking(from: nine).valid? # 9am has gone
assert booking(from: nine + 1.hour).valid? # 10am is still ahead
end
It fails as predicted, and the code is one validation:
validate :starts_in_the_future, on: :create
def starts_in_the_future
errors.add(:starts_at, "is in the past") if starts_at&.past?
end
Now imagine the five overlap tests without the travel_to in setup. On 28 May 2024 they pass, because 8 June is in the future. On 9 June every one of them fails, on a Sunday, in continuous integration (CI), for a reason that has nothing to do with the code anyone changed. Fixed dates in tests are fine only when the clock is frozen next to them. The other habit worth having: always ask Rails for Time.current and Date.current, which respect the application's time zone, rather than Time.now26.
Running the whole suite after this cycle found one more casualty. The cancelled slot test from the first decisions chapter rebooks the fixture time of 10 February 2024, which is now in the past, so the new validation refuses it. It gets a travel_to in its setup as well, and the suite is green again.
Stopping real HTTP with WebMock
Cogwell's nightly reorder report asks the parts wholesaler for current prices over HTTP. A test that calls the real wholesaler is slow, fails when their server does, and might place a real order. WebMock stops all real HTTP connections in tests and lets you declare what each request should return27.
# Gemfile
group :test do
gem "webmock"
end
# test/test_helper.rb (addition)
require "webmock/minitest" # from now on, any real HTTP request in a test raises an error
The client being tested is small on purpose:
# app/models/wholesaler_client.rb
require "net/http"
class WholesalerClient
BASE = "https://api.wholesaler.example"
def price_pence(sku)
response = Net::HTTP.get_response(URI("#{BASE}/v1/prices/#{sku}"))
raise "Wholesaler answered #{response.code}" unless response.is_a?(Net::HTTPSuccess)
JSON.parse(response.body).fetch("price_pence")
end
end
And the test declares the wholesaler's answer:
# test/models/wholesaler_client_test.rb
require "test_helper"
class WholesalerClientTest < ActiveSupport::TestCase
test "reads the current price of a part" do
stub_request(:get, "https://api.wholesaler.example/v1/prices/CHN-11SP")
.to_return(status: 200, body: { price_pence: 1_250 }.to_json,
headers: { "Content-Type" => "application/json" })
assert_equal 1_250, WholesalerClient.new.price_pence("CHN-11SP")
end
test "a server error from the wholesaler is raised, not swallowed" do
stub_request(:get, "https://api.wholesaler.example/v1/prices/CHN-11SP").to_return(status: 503)
assert_raises(RuntimeError) { WholesalerClient.new.price_pence("CHN-11SP") }
end
end
The second test is the one people skip, and it is the one that matters at 2am when the wholesaler is down.
If the system tests later need a local browser driver to download something, WebMock.disable_net_connect!(allow_localhost: true) allows connections to your own machine and keeps the rest blocked27.
Recording real answers with VCR
A hand written stub is only as accurate as your memory of the real API. VCR records a real HTTP exchange once into a YAML file, a cassette, and replays it in every later run28. It hooks into WebMock, and filter_sensitive_data replaces API keys in the recording so they never reach the repository.
# test/test_helper.rb (addition)
require "vcr"
VCR.configure do |config|
config.cassette_library_dir = "test/cassettes"
config.hook_into :webmock
config.filter_sensitive_data("<WHOLESALER_KEY>") { Rails.application.credentials.dig(:wholesaler, :api_key) }
end
test "reads a price from a recorded wholesaler answer" do
VCR.use_cassette("wholesaler_price_chain") do
assert_kind_of Integer, WholesalerClient.new.price_pence("CHN-11SP")
end
end
My view: stubs for behaviour you design (errors, timeouts, odd answers), cassettes for the shape of real answers, and a reminder in the calendar to record cassettes again, because a recording from last year proves only that last year's API worked.
Parallel testing: built in, with a fixed cost
Rails 6.0 added parallel testing29, and Rails 7.1 generates it switched on. By default Rails forks one process per CPU core. Each process gets its own test database, created and loaded with the schema automatically, with the worker number added to its name. You can set the number of workers in test_helper.rb or with the PARALLEL_WORKERS environment variable, and switch to threads instead of processes with with: :threads4.
Parallel runs are not free. The guide says plainly that they add overhead for database setup and fixture loading, which is why Rails does not parallelise a run of fewer than 50 tests. The threshold is configurable with config.active_support.test_parallelization_threshold4. When a forked worker needs its own resources, such as a separate folder for uploaded files, the parallelize_setup and parallelize_teardown hooks run once per worker4.
A simple model shows why more workers stop helping at some point. Split the run into a fixed part, which no number of workers makes shorter, and a part that divides between workers (Foundations: ratios and rates):
where is the time of a full run with workers, is the fixed part (booting Rails, creating the worker databases, loading fixtures), is the part that divides between workers (running the tests themselves), and is the number of workers.
The speedup compared with one worker, on the same Foundations page, is
where is how many times faster the run is with workers, and is the run time with a single worker. As grows, approaches , so the speedup can never exceed .
Example: Cogwell's suite after six months (illustrative)
These figures are illustrative, chosen to show the shape, not measured. After six months Cogwell's suite has 640 tests and takes 240 seconds with one worker. Of that, 12 seconds is fixed: and .
- One worker: seconds.
- Two workers: seconds.
- Four workers: seconds.
- Eight workers: seconds, a speedup of .
The ceiling is times, however many cores you buy. In practice the fixed part grows a little with each worker, because each one creates its own database, so real curves flatten earlier than this one.
The lesson for the person writing tests: once parallelism is on, the only way to make the run much faster is to shrink both parts. Fewer rows written per test shrinks . A lean fixture world and a fast boot shrink . That brings us back to the data decision.
Speed habits that keep TDD bearable
TDD only works if running a test is quicker than thinking about whether to run it. These habits keep the loop under a few seconds. Each is documented in the Rails guide or the library's own docs, and the selection is mine.
- Run one test, not the suite.
bin/rails test test/models/booking_test.rb:14runs the test on line 14. Editors can bind this to a key. Run the whole suite before you commit, not after every keystroke. - Fail fast when the suite is red.
bin/rails test --fail-faststops at the first failure, which is what you want when a refactor broke something4. - Find the slow ones.
bin/rails test --profilelists the ten slowest tests4. Look at them once a month. The slowest test is usually slow because of data, not logic. - Climb only as high as the rule. The price tests run in microseconds because they never touch the database. Every rule you can test without a request or a browser is time saved on every run, forever.
- Write fewer rows. Fixtures for the world, explicit records for the rule. With factories, prefer
buildandbuild_stubbedand reach forcreateonly when the test needs the row17. - Keep system tests few.
bin/rails testalready leaves them out, andbin/rails test:allincludes them4. Run them in CI and before a release, and cover each journey once. - Keep random order on. Random order finds tests that only pass because another test ran first. When it catches one, the run prints a seed, and
bin/rails test --seed 1234repeats the exact order so you can reproduce it47. - Never sleep. A test that waits for "long enough" is slow on a fast machine and flaky on a slow one. Freeze time with
travel_to, and perform jobs withperform_enqueued_jobsinstead of waiting for them426.
| Habit | Command or tool | What it saves |
|---|---|---|
| Run one test | bin/rails test path:line | Seconds on every cycle |
| Stop at the first failure | bin/rails test --fail-fast | Scrolling through 40 failures caused by one bug |
| Find the slowest tests | bin/rails test --profile | Guessing where the time goes |
| Reproduce an order bug | bin/rails test --seed N | Days of "it only fails in CI" |
| Freeze the clock | travel_to, freeze_time | Tests that break on a date |
| Block the network | webmock/minitest | Slow, flaky and dangerous real calls |
| Parallel runs | parallelize(workers: :number_of_processors) | Most of the wall clock time, up to the fixed part |
For the person paying for this
If you commission a Rails application, you do not need to read the tests to judge them. Ask four questions, and expect plain answers.
- How long does the full suite take, and when does it run? A good answer is a number of minutes and "on every change, automatically". "We run it before releases" means bugs reach the release.
- Show me the test for the last bug you fixed. A team that writes tests first can point to a test that failed before the fix and passes after it. In my judgement, that one habit says more about whether a bug stays fixed than any coverage figure.
- What is not tested, and why? Every suite has gaps. A team that can name theirs is in control of them.
- Minitest or RSpec? Either answer is fine. If someone proposes rewriting a working suite from one to the other, ask what customer problem it solves.
The choice of test library should never appear as a cost on your invoice. Test data, test speed and the habit of writing the test first decide what your application costs to change in year three. If you want to talk that through for your own project, my web application development page explains how I work, and my prices are published on the transparent pricing page. Or book the free workshop and bring your test suite along.
Conclusion
Test driven development in Rails is less about the library than the tutorials suggest. Minitest and RSpec are two dialects for the same conversation. Start with Minitest on a new application because Rails is built around it, keep RSpec if your team already speaks it well, and spend the energy you saved on the decisions that cost: how you create test data, which level each rule is tested at, and how fast the loop stays.
The loop itself is simple and strict. Write the test list with the person who owns the rule. Predict every red before you see it. Write the least code that passes, then refactor while green. Test each rule at the lowest level that can see it: plain Ruby for the price, a model test for the overlap, a request test for the status and the message, a constraint for the twin. Freeze the clock, block the network, and keep the run short enough that you never hesitate to press the key.
Next week the outer loop: BDD and end to end testing in Rails with Cucumber, Capybara and system tests. The Django version of this chapter follows in two weeks, on the same booking rule and the same price, so you can compare the two like for like.
