A test suite you can trust: CI, speed and flaky tests in Rails and Django
TL;DR
Difficulty: Advanced
A test suite answers one question on every push: is it safe to ship? Judge it by time to answer and by red precision, the share of red builds where something was really broken.
- Complete GitHub Actions workflows for Rails 7.1 and Django 5.0: services only if tests use them, cached dependencies, browser tests split over two machines, screenshots and traces on failure, deploy only from green main.
- Speed comes mostly from removal: profile first, parallel workers, fewer browser tests (would it pass with JavaScript off?), lean test data, a fast password hasher in Django.
- Twelve tests that each flake 2% of the time make one build in five red for nothing. Fix the six causes, quarantine with a limit, rerun only to diagnose.
- In the example, 19 and 22 minutes become about 4.5 and 5.
Most test suites fail in one of two ways: too slow to wait for, or too flaky to believe. This closing chapter of the testing series shows complete CI workflows for Rails and Django, takes one example application's two suites from 19 and 22 minutes to under seven, and turns a red build back into something people stop for.
A test suite answers one question. It has to answer fast, and it has to be right.
Every time a developer pushes a change, the test suite is asked one question: is it safe to ship this?
It can answer badly in two ways. Slowly, so people stop waiting and push the next change on top. Or wrongly, so people stop believing it and press "rerun" until it turns green. Both end with broken code in production and a green tick next to it. So I judge a suite by two numbers:
- Time to answer. Minutes from push to a green or red result. Kent Beck made the ten minute build a core practice of Extreme Programming in 20041, and Martin Fowler's article on continuous integration still calls that guideline "perfectly within reason" for most projects2.
- Red precision. Of all the red builds last month, the share where something was actually broken. Nobody measures this, and it is the number that decides whether a suite is trusted.
A suite that takes 25 minutes is annoying. A suite with a red precision of 34% is worse: two out of three alarms are false, so people learn to ignore the alarm. My rule of thumb: A rerun on red is the moment a suite stops answering. Treat every one as a bug report.
This is the last chapter of the testing series and of the programme. It assumes the test types from the testing map and the toolchains from the chapters after it, as of June 2024: Rails 7.1 on Ruby 3.3, Django 5.0 on Python 3.12.
Example: two suites that stopped answering
The example is invented, and it is the one the whole programme has built. Cogwell Cycles is a chain of bicycle repair workshops in Sheffield (cogwellcycles.example), founded by Hannah. Two years after launch it has 14 workshops, 95 mechanics and about 3,100 repair bookings a week. Priya and Owen built the core in both frameworks, and this series followed both versions. As in growing a Rails application, the team is now four developers (my assumption).
| Fact | Rails version | Django version |
|---|---|---|
| Tests | 1,450 | 1,380 |
| Browser tests | 38 system tests | 34 end to end tests |
| Time in continuous integration (CI) | 19 minutes | 22 minutes |
| Target | under 7 minutes | under 7 minutes |
| Pushes that trigger CI (my assumption) | about 20 a day | about 20 a day |
Hannah does not read test output. She notices two things. Small fixes take half a day to reach production. And last month a bug in the VAT line of the invoice went live on a day when, as Owen put it, "the build was red anyway, it's always that board test". The test that would have caught the invoice bug was red as well. Nobody looked.
The rest of this chapter takes both suites to under 7 minutes, and from "always red anyway" to a red that means something.
Continuous integration from first principles
Continuous integration is older than any of the tools that run it. Fowler's definition: each member of a team merges their changes into a shared codebase at least daily, and each merge is verified by an automated build, including the tests, to detect integration errors as quickly as possible2. Fowler first wrote it up in 2000 and revised the article in January 2024.
Three ideas are packed into that definition:
- One mainline. Everybody's work meets in one branch, usually
main, often. Long lived branches postpone the integration problem until it is large. - A self testing build. "It compiles" proves little. The build runs the tests, and a failing test fails the build.
- A machine does it, every time. Not "I ran the tests on my laptop". A clean machine that nobody configured by hand, so a missing file or an undeclared dependency cannot hide.
A CI service is that machine, rented. You describe the steps in a file in your repository, and on every push it starts a fresh virtual machine, runs them and reports green or red on the pull request.
The words GitHub Actions and GitLab CI use
I show GitHub Actions in full below. GitLab CI works on the same ideas with slightly different words.
| Idea | GitHub Actions | GitLab CI |
|---|---|---|
| The file | .github/workflows/ci.yml (any name in that folder)3 | .gitlab-ci.yml at the root4 |
| A unit of work on one machine | a job | a job |
| A command inside a job | a step | a line under script |
| A database next to the job | services with a container image5 | services with a Docker image4 |
| The same job several times | strategy.matrix3 | parallel: N, with CI_NODE_INDEX and CI_NODE_TOTAL set in each copy4 |
| Files kept after the run | an artefact via actions/upload-artifact6 | artifacts |
| Order between jobs | needs | stages or needs |
One fact matters for speed later. As of June 2024, a standard GitHub hosted Linux runner for a private repository has two processor cores and 7 GB of memory, and ubuntu-latest means Ubuntu 22.047. Public repositories got four cores in January 2024. Cogwell's code is private, so two cores it is.
Example: Cogwell's pipeline as a flow
Before writing YAML, Priya draws what should happen on every push. The order matters: quick checks first, so a typo fails in one minute instead of after the browser tests.
In the real workflow, the unit job and the browser jobs run at the same time, not one after the other. The flow shows them in sequence only because they all have to be green before the decision.
The Rails workflow, complete
Rails 7.1 generates a Dockerfile but no CI file, so you write this one yourself. It has three jobs: unit and integration tests, browser tests on two machines, and a deploy that only runs when both are green on main.
Example: Cogwell's .github/workflows/ci.yml for Rails
The top of the file says when to run, cancels a superseded run on the same branch, and sets what every job shares.
# .github/workflows/ci.yml
name: CI
on:
pull_request:
push:
branches: [main]
# A newer push to the same branch cancels the older run.
concurrency:
group: ci-${{ github.ref }}
cancel-in-progress: true
env:
RAILS_ENV: test
DATABASE_URL: postgres://postgres:postgres@localhost:5432/cogwell_test
REDIS_URL: redis://localhost:6379/0
The first job runs everything except the browser tests. The two services are containers that GitHub starts next to the job and waits for, using the health check, before the first step runs5.
jobs:
test:
name: Unit and integration tests
runs-on: ubuntu-22.04
timeout-minutes: 15
services:
postgres:
image: postgres:16
env:
POSTGRES_PASSWORD: postgres
ports: ["5432:5432"]
options: >-
--health-cmd pg_isready
--health-interval 10s
--health-timeout 5s
--health-retries 5
redis:
image: redis:7
ports: ["6379:6379"]
options: >-
--health-cmd "redis-cli ping"
--health-interval 10s
--health-timeout 5s
--health-retries 5
steps:
- uses: actions/checkout@v4
- uses: ruby/setup-ruby@v1
with:
bundler-cache: true # runs bundle install and caches the gems
- name: Prepare the database
run: bin/rails db:create db:schema:load
- name: Run the tests and list the 20 slowest
run: bin/rails test --profile 20
ruby/setup-rubyreads the Ruby version from.ruby-version, andbundler-cache: truerunsbundle installand caches the installed gems between runs8. The largest saving in this chapter for the least effort.db:schema:loadbuilds the test database fromdb/schema.rbinstead of replaying two years of migrations.bin/rails testruns every test except system tests. The Rails testing guide says so plainly, because system tests "can be slow"9.--profile 20lists the 20 slowest tests at the end9, the measurement for the next section.- GitHub Actions sets the variable
CIon every runner10. Theconfig/environments/test.rbthat Rails 7.1 generates containsconfig.eager_load = ENV["CI"].present?, so a file that only breaks when the whole application loads is caught before deploy11.
Why Redis, when the Rails test environment uses Action Cable's test adapter and a null cache store? Because a handful of Cogwell's tests check the cached day totals against a real Redis cache store. The rule: start a service in CI only if a test talks to it. A Redis container that no test uses makes the pipeline slower and suggests a safety that does not exist.
The second job runs the system tests, split over two machines with a matrix.
system:
name: System tests, group ${{ matrix.group }} of 2
runs-on: ubuntu-22.04
timeout-minutes: 15
strategy:
fail-fast: false # let both groups finish, to see every failure
matrix:
group: [1, 2]
services:
postgres:
image: postgres:16
env:
POSTGRES_PASSWORD: postgres
ports: ["5432:5432"]
options: >-
--health-cmd pg_isready
--health-interval 10s
--health-timeout 5s
--health-retries 5
steps:
- uses: actions/checkout@v4
- uses: ruby/setup-ruby@v1
with:
bundler-cache: true
- run: bin/rails db:create db:schema:load
- run: bin/rails tailwindcss:build
- name: Run this machine's share of the system tests
run: |
files=$(find test/system -name "*_test.rb" | sort |
awk -v n=2 -v g=${{ matrix.group }} 'NR % n == g % n')
bin/rails test $files
- name: Keep the screenshots of failed tests
if: failure()
uses: actions/upload-artifact@v4
with:
name: screenshots-group-${{ matrix.group }}
path: tmp/screenshots
retention-days: 7
The split is deliberately plain: sort the files, give every second one to each machine. No gem, and anyone can read it. A split by recorded timings balances better, more on that below.
When a system test fails, Rails takes a screenshot automatically9 and saves it under tmp/screenshots12. The last step uploads that folder when something failed, so the developer sees what the browser saw.
One change makes the system tests CI ready. The generated ApplicationSystemTestCase opens a visible Chrome window, which a runner does not have:
# test/application_system_test_case.rb
require "test_helper"
class ApplicationSystemTestCase < ActionDispatch::SystemTestCase
# Headless on CI, a visible window on a laptop for debugging.
driven_by :selenium,
using: ENV["CI"] ? :headless_chrome : :chrome,
screen_size: [1400, 1400]
end
The third job deploys, and only when both test jobs are green on a push to main:
deploy:
needs: [test, system]
if: github.ref == 'refs/heads/main' && github.event_name == 'push'
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v4
- uses: ruby/setup-ruby@v1
with:
bundler-cache: true
- name: Deploy
run: bin/deploy # Cogwell's script around Kamal, yours may call a platform's CLI
needs is the gate: GitHub does not start the deploy job unless every job it needs has succeeded3. If you use Cucumber for the scenarios a business person reads, as the Rails BDD chapter discusses, add bundle exec cucumber to the system job in the same way.
The Django workflow, complete
The Django version has the same shape: one job for everything without a browser, two machines for the browser tests, a deploy behind both. The tools differ. Cogwell's Django suite uses pytest with pytest django, factory boy for test data, and Playwright for the browser, as built in the Django TDD chapter and the Django end to end chapter.
Example: Cogwell's .github/workflows/ci.yml for Django
The shared part. The settings for tests live in their own module, shown after the workflow.
# .github/workflows/ci.yml
name: CI
on:
pull_request:
push:
branches: [main]
concurrency:
group: ci-${{ github.ref }}
cancel-in-progress: true
env:
DJANGO_SETTINGS_MODULE: cogwell.settings_test
SECRET_KEY: only-for-ci
DATABASE_URL: postgres://postgres:postgres@127.0.0.1:5432/cogwell
REDIS_URL: redis://127.0.0.1:6379/0
The first job. The services block is identical to the Rails one, so I shorten it here.
jobs:
test:
name: Unit and integration tests
runs-on: ubuntu-22.04
timeout-minutes: 15
services:
postgres: { image: "postgres:16", env: { POSTGRES_PASSWORD: postgres }, ports: ["5432:5432"],
options: "--health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5" }
redis: { image: "redis:7", ports: ["6379:6379"],
options: "--health-cmd \"redis-cli ping\" --health-interval 10s --health-timeout 5s --health-retries 5" }
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.12"
cache: pip # caches downloaded packages
cache-dependency-path: requirements*.txt
- run: pip install -r requirements.txt -r requirements-dev.txt
- name: Migrations match the models
run: python manage.py makemigrations --check --dry-run
- name: Run the tests, two workers, list the 20 slowest
run: pytest -n auto -m "not e2e and not quarantine" --durations=20 --cov
actions/setup-pythonwithcache: pipcaches downloaded packages, keyed on the requirements files13. The pinnedrequirements.txtcomes from pip tools, as set up in starting a new Django project.makemigrations --check --dry-runfails the build when someone changed a model and forgot the migration.-n autocomes from pytest xdist and starts one worker per processor core14. pytest django gives each worker its own test database by adding a suffix to its name15.-m "not e2e and not quarantine"leaves out the browser tests (their own job) and the quarantined tests (explained later).
The browser job installs Chromium for Playwright and splits the end to end tests by their recorded durations with pytest split16:
e2e:
name: End to end tests, group ${{ matrix.group }} of 2
runs-on: ubuntu-22.04
timeout-minutes: 15
strategy:
fail-fast: false
matrix:
group: [1, 2]
services:
postgres: { image: "postgres:16", env: { POSTGRES_PASSWORD: postgres }, ports: ["5432:5432"],
options: "--health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5" }
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.12"
cache: pip
cache-dependency-path: requirements*.txt
- run: pip install -r requirements.txt -r requirements-dev.txt
- run: python -m playwright install --with-deps chromium
- name: Run this machine's share of the end to end tests
run: >
pytest -m "e2e and not quarantine"
--splits 2 --group ${{ matrix.group }} --splitting-algorithm least_duration
--tracing retain-on-failure --screenshot only-on-failure --output test-results
- name: Keep traces and screenshots of failed tests
if: failure()
uses: actions/upload-artifact@v4
with:
name: playwright-group-${{ matrix.group }}
path: test-results
retention-days: 7
deploy:
needs: [test, e2e]
if: github.ref == 'refs/heads/main' && github.event_name == 'push'
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v4
- name: Deploy
run: ./deploy.sh # Cogwell's deploy script, yours may call a platform's CLI
pytest split reads a .test_durations file that you create with pytest --store-durations and commit. Its least_duration algorithm gives each test to the group with the smallest total so far, which its README says balances better than the default16. The Playwright options keep a trace and a screenshot of every failed test in test-results17. A trace records every action, network request and page state, and playwright show-trace replays it: the closest thing to having been on the machine.
The test settings, and the pytest configuration:
# cogwell/settings_test.py
from .settings import * # noqa: F401,F403 (everything else as in production)
# The default PBKDF2 hasher is slow on purpose. Tests do not need that.
PASSWORD_HASHERS = ["django.contrib.auth.hashers.MD5PasswordHasher"]
# Job card photos go to memory, never to disk or to the bucket.
STORAGES = {
"default": {"BACKEND": "django.core.files.storage.InMemoryStorage"},
"staticfiles": {"BACKEND": "django.contrib.staticfiles.storage.StaticFilesStorage"},
}
# pyproject.toml (extract)
[tool.pytest.ini_options]
DJANGO_SETTINGS_MODULE = "cogwell.settings_test"
addopts = "--reuse-db --allow-hosts=127.0.0.1,::1"
markers = [
"e2e: drives a real browser through the live server",
"quarantine: known to be flaky, has an owner and a ticket",
]
Both settings come up again below: the password hasher in the section on test data, and --allow-hosts in the section on external services.
Measure before you speed anything up
The temptation with a slow suite is to buy a bigger machine or to start splitting. Both hide the real problem when a few tests eat most of the time. Find those few first:
# Rails 7.1: the 20 slowest tests at the end of the run
bin/rails test --profile 20
# Django 5.0 on Python 3.12, with Django's own runner
python manage.py test --durations 20
# pytest, which the Django version of Cogwell uses
pytest --durations=20
The Rails option is in the 7.1 test runner9. Django added --durations in 5.0, for Python 3.12 or later18 19.
Read the list with one question: why is this test slow, and does the slowness belong to what it tests? A browser test that takes eight seconds because it walks through a booking is honest. A model test that takes two seconds because it builds a mechanic with a hashed password, three workshops and 40 parts is not.
Example: what Cogwell's 20 slowest tests had in common
Priya runs the profile on both versions and sorts the 20 slowest tests of each into causes. These groupings are mine for the example. The shape is typical.
| Cause | Rails | Django | Fix |
|---|---|---|---|
| Browser test that does not need a browser | 7 | 6 | move it down to a request test |
| Test data builds far more than the test reads | 5 | 5 | build less, see the test data section |
| Password hashing in user factories | 0 | 4 | a fast hasher in test settings |
| Photo processing for job cards | 3 | 2 | in memory storage, no image variants |
| A real HTTP call that times out | 2 | 2 | block the network, stub the SMS provider |
| Genuinely slow, and worth it | 3 | 1 | keep |
Only four of 40 tests were slow for a good reason. Speed work is mostly removal, not engineering.
The password row is a fair difference between the frameworks, not a weakness of either. Rails sets ActiveModel::SecurePassword.min_cost in the test environment, so has_secure_password uses the lowest bcrypt cost in tests without anyone asking20. Django keeps its production hasher unless you change it: 720,000 PBKDF2 iterations in Django 5.018. The Django testing documentation itself suggests a faster hasher in test settings21. Cogwell's Django factories create a user for every mechanic, so that one setting saves about two minutes.
Parallel on one machine, then split across machines
There are two kinds of parallelism, and they solve different problems.
Parallel workers on one machine use all the processor cores. A new Rails 7.1 application's test_helper.rb contains parallelize(workers: :number_of_processors), Rails forks one process per core with its own copy of the test database, and it does not bother below 50 tests, which is the default threshold9. Django's runner has --parallel, where auto means one process per core and each process gets its own database19. In pytest, the xdist plugin does the same with -n auto14.
Splitting across machines runs several jobs at once, each with a share of the tests. This is the only way past the number of cores, and on a private GitHub runner that number is two7.
The wall clock time of a split run follows a simple formula, and it explains why balance matters as much as the number of machines:
- is the time from push to result for that stage.
- is what every machine pays before the first test: checkout, cache restore, database, browser.
- is the number of machines.
- is the test time on machine . The stage waits for the slowest machine, hence the maximum.
The ideal is for every machine. Setup is paid on every machine, so adding machines stops paying when approaches the per machine test time. More on ratios like this in Foundations: ratios and rates.
Example: two machines or three for Cogwell's browser tests
After the other fixes below, Cogwell's Rails system tests take 5.2 minutes in one go, and setup is about 1.2 minutes (gems from the cache, database, Tailwind build).
- One machine: minutes.
- Two machines, well balanced: minutes.
- Three machines: minutes.
Two machines save 2.6 minutes, a third only 0.9 more. And the unit job runs at the same time and takes about 3.8 minutes anyway, so a third browser machine would not change the total at all. Two it is.
Balance matters too. If one machine draws the three longest journeys, its share might be 3.4 minutes instead of 2.6, and the stage takes minutes. When test lengths differ a lot, split by recorded time: pytest split with least_duration in Python16, the knapsack or parallel_tests gems in Ruby.
The parallelism trap
Parallel workers expose every test that depends on another test's leftovers: a shared counter, a file at a fixed path, a cache nobody clears. The suite that passed in one process fails one run in ten with two.
The tempting response is to switch parallelism off. A year ago Owen set PARALLEL_WORKERS=1 in CI to make a flaky week go away. The flaky week went away. The shared state stayed, and the suite has run on one core ever since.
My rule: switching off parallelism to stop flaky tests is a rerun in disguise. It hides the symptom and keeps the cause. Fix the shared state (below) and parallelism comes back for free.
Database strategies that keep tests fast and isolated
The database is where most test time and most test pollution live. The good news: both frameworks get the default right.
- Rails wraps every test in a database transaction and rolls it back at the end9. Since Rails 5.1, extra threads, such as the server thread a system test starts, share the test's connection inside its transaction, so system tests roll back too22. You only lose this with
self.use_transactional_tests = false, and then you clean up yourself. - Django's
TestCasealso wraps each test in a transaction.TransactionTestCaseandLiveServerTestCasecannot, because the live server runs in another thread with its own connection, so they empty the tables after each test instead, which is slower21. In pytest django the same split appears as thedbandtransactional_dbfixtures, and thelive_serverfixture that Playwright tests use needs the transactional one. The Django end to end chapter explains that trap in detail.
Three habits make the database faster still.
- Reuse the test database on your laptop. pytest django's
--reuse-dbkeeps it between runs,--create-dbrebuilds it after schema changes15. Django's own runner calls it--keepdb21. In CI there is nothing to reuse, and the option does no harm. - Build the schema, do not replay it. Rails loads
db/schema.rb. Django runs the migrations, which gets slower as they pile up. pytest django's--no-migrationsbuilds tables straight from the models15. My view: keep the migrations in CI, because they are what production runs, and squash old ones when they really hurt. - Prefer the transactional test case. Use the truncating kind only when a second connection must see the data, which in practice means browser tests.
Example: one booking test, both ways
The overlap rule from the Rails TDD chapter is enforced by a database constraint, so its test needs the database, but no browser and no second connection. It runs inside a transaction in both versions.
# test/models/booking_overlap_test.rb
require "test_helper"
class BookingOverlapTest < ActiveSupport::TestCase
test "a second booking for the same mechanic and time is rejected" do
first = bookings(:saturday_ten_am) # a fixture, loaded once per run
clash = first.dup # same mechanic, same slot
assert_raises(ActiveRecord::StatementInvalid) { clash.save!(validate: false) }
end
end
# bookings/tests/test_overlap.py
import pytest
from django.db import IntegrityError
from bookings.tests.factories import BookingFactory
@pytest.mark.django_db # a transaction per test, rolled back afterwards
def test_second_booking_for_same_mechanic_and_time_is_rejected():
first = BookingFactory()
with pytest.raises(IntegrityError):
BookingFactory(mechanic=first.mechanic, starts_at=first.starts_at, ends_at=first.ends_at)
Neither test leaves a row behind. Either can run in any order, in any worker, as often as you like.
Fewer browser tests, not faster browser tests
Browser tests are the slowest and the flakiest tests you have. On Cogwell's Rails suite, 38 system tests take 9 of the 19 minutes. On the Django suite, 34 end to end tests take 10 of the 22. They are also the most valuable when they test a journey a customer actually takes, with the real JavaScript. The skill is keeping those and moving the rest down a level.
Here is the test I use for that, and I call it the switch off test. Ask of every browser test: would it still pass with JavaScript switched off in the browser? If yes, the behaviour it checks is plain HTML from the server, and a request test checks the same thing in a fraction of the time. If no, it may well need the browser: Turbo Streams on the workshop board, an htmx swap, a Stimulus controller, a date picker.
It is not a perfect rule. A full booking journey can still be worth one browser test as a smoke test for the page as a whole. But it sorts most of the list in an afternoon.
Example: Cogwell's 38 system tests, sorted
Owen goes through the 38 Rails system tests with the question. The Django team does the same for its 34, with a similar result.
| Group | Tests (Rails) | Passes without JavaScript? | Decision |
|---|---|---|---|
| Booking form validation messages | 5 | yes | request tests |
| Back office filters and sorting | 4 | yes | request tests |
| Login redirects for the three roles | 3 | yes | request tests |
| Invoice download links | 2 | yes | request tests |
| Full booking journey, customer side | 4 | yes | keep, as journey smoke tests |
| Workshop board, live updates with two sessions | 6 | no | keep |
| Job card photo upload with preview | 3 | no | keep |
| Slot picker | 5 | no | keep |
| Everything else | 6 | no | keep |
14 tests move down and 24 stay. On the Django side, 12 of 34 move down and 22 stay. Here is one moved test in each framework: the booking form rejecting a slot in the past.
# test/integration/booking_validation_test.rb (was a system test)
require "test_helper"
class BookingValidationTest < ActionDispatch::IntegrationTest
test "a slot in the past is rejected with a message" do
post bookings_path, params: { booking: {
workshop_id: workshops(:kelham).id,
starts_at: 1.day.ago
} }
assert_response :unprocessable_entity
assert_select ".error", text: /in the past/
end
end
# bookings/tests/test_booking_validation.py (was an end to end test)
from datetime import timedelta
import pytest
from django.urls import reverse
from django.utils import timezone
from bookings.tests.factories import WorkshopFactory
@pytest.mark.django_db
def test_slot_in_the_past_is_rejected_with_a_message(client):
response = client.post(reverse("bookings:create"), {
"workshop": WorkshopFactory().pk,
"starts_at": timezone.now() - timedelta(days=1),
})
assert response.status_code == 422 # set by Cogwell's view on invalid forms
assert "in the past" in response.content.decode()
Both run in well under a tenth of a second. The browser version took about 14 seconds each. The behaviour checked is the same.
Test data that does not build the world
The second biggest time sink is test data, nearly always a factory that creates a whole graph of records when the test reads one attribute. Rails fixtures avoid this by loading once and being shared9. Factories, which the Rails TDD chapter compares with fixtures, are clearer per test and slower when overused. Three habits keep them fast:
- Build, do not save, when you can. factory bot has
buildandbuild_stubbedfor objects that never touch the database. factory boy hasFactory.build(). A price calculation does not need a saved row. - Make associations lazy or explicit. A
JobCardFactorythat creates a booking, which creates a customer, a bike, a mechanic and a workshop, turns one line in a test into six inserts. Pass the parent in when the test already has one. - Never hash a real password in a factory you call 400 times. Covered above for Django. In Rails the minimum bcrypt cost does it for you.
Example: the job card factory, before and after
Cogwell's Django JobCardFactory used SubFactory all the way down. Priya counts the inserts with django_assert_num_queries, a pytest django fixture, and gets 11 for one job card. The price test only needs a job card in memory with two parts on it.
# repairs/tests/test_price.py
from decimal import Decimal
from repairs.tests.factories import JobCardFactory, PartUsageFactory
def test_price_is_labour_plus_parts_plus_vat():
card = JobCardFactory.build(labour_minutes=90) # no database at all
usages = PartUsageFactory.build_batch(2, job_card=card, unit_price=Decimal("12.00"))
# 1.5 hours at £45 = £67.50, parts £24.00, subtotal £91.50, VAT 20% = £18.30
assert card.total_with_vat(usages) == Decimal("109.80")
The test no longer needs django_db at all, so it runs without touching PostgreSQL. Across the suite, moving 300 tests from create to build saved about 40 seconds on Cogwell's Django version, and the equivalent change with build_stubbed saved a similar amount on Rails. Small, but it compounds with everything else.
Flaky tests: what they are and what they cost
A flaky test passes and fails on the same code. That is Google's definition in John Micco's 2016 report, which also gives the scale in a very large codebase: about 1.5% of all test runs reported a flaky result, almost 16% of tests showed some flakiness, and about 84% of the pass to fail transitions their CI observed involved a flaky test23. Most "this just broke" signals were noise.
Martin Fowler's 2011 essay explains why this is worse than a slow suite. A test that fails at random is useless as a regression test, and the habit of ignoring it spreads to the healthy tests next to it24. That is exactly how the VAT bug got through at Cogwell.
How a small flake rate becomes a red build every few runs
If a suite contains flaky tests, and each fails at random with probability on a run, independently, then the chance that a run is red for no reason is:
- is the probability that at least one flaky test fails on a run.
- is the chance that one flaky test fails on one run.
- is the number of flaky tests in the suite.
- is the chance that all of them pass, so one minus that is the chance that at least one fails.
The background is in Foundations: probability.
Now add real failures. If a fraction of runs contain a real bug, red precision, the share of red builds that are real, is:
- is the chance that a run contains a real failure, assumed to turn it red. It is the numerator.
- is the chance that a run has neither a real failure nor noise, so one minus it is the chance that a run is red at all.
- is the share of red runs that are real. See Foundations: probability for conditional chances like this one.
And if people simply rerun until green, the expected time to a green answer for a change that is actually fine grows from to:
- is the time of one run.
- is the chance that a run of a correct change comes back green.
- is the expected total time until the first green run, the expected value of a run repeated until it succeeds, explained in Foundations: expected value.
Example: what the formulas say about Cogwell's suite
Priya goes through three months of CI history on the Rails version. She looks for runs where a test failed and then passed on the same commit without a code change. 12 tests show up, each failing in roughly 2% of runs.
- . About one run in five is red for no reason.
- Assume one run in ten contains a real failure, . Then precision is .
- With minutes, minutes.
Two out of three red builds at Cogwell were false alarms. No wonder nobody looked at the VAT failure. Each of those 12 tests passes 98 times in 100, and each one looks harmless alone. Together they destroy the signal.
The lesson from the formula: flakiness adds up across tests, and trust collapses long before any single test looks bad. That is why the policy later in this chapter treats one flaky test as an incident, not as noise.
The six causes of flaky tests, and the fix for each
Nearly every flaky test I have read about, and every one in the literature, comes down to one of six causes. Fowler's essay groups them a little differently, as lack of isolation, asynchronous behaviour, remote services, time and resource leaks24. I split isolation into its two common forms and add randomness, because each needs a different fix.
The numbers are illustrative, but the order is the usual one: browser timing first, time second.
Cause 1: asynchronous user interfaces
The browser does things later than the test expects. A Turbo Stream arrives 300 milliseconds after the click, an htmx swap waits for the server, and the test has already checked.
Both Capybara and Playwright solve this by waiting. Capybara's finders and matchers retry until the element appears or the default maximum wait time passes, which is two seconds unless you change it25. Playwright waits automatically before actions and in its expect assertions17. Flakiness comes from code that bypasses the waiting: a sleep, a check that reads a value once, or a negative check written the wrong way.
Example: the workshop board test
# Flaky: reads the page once, right after the click.
click_on "Start repair"
assert page.find("#job_card_42").text.include?("In repair")
# Flaky in a different way: a guess at how long Turbo takes.
click_on "Start repair"
sleep 1
assert_text "In repair"
# Stable: Capybara retries the assertion until it passes or times out.
click_on "Start repair"
within("#job_card_42") { assert_text "In repair" }
# Flaky: reads the text once.
page.get_by_role("button", name="Start repair").click()
assert "In repair" in page.locator("#job_card_42").inner_text()
# Stable: Playwright's expect retries until the text appears.
page.get_by_role("button", name="Start repair").click()
expect(page.locator("#job_card_42")).to_contain_text("In repair")
The Rails BDD chapter shows how many flaky failures disappeared when the sleeps went. The same holds in Django.
Cause 2: time and dates
Tests that use the real clock pass all day and fail at 11pm, on the last day of the month, or on the night the clocks change. Fowler's advice is to wrap the clock so a test can set it24. Rails ships travel_to and freeze_time in ActiveSupport::Testing::TimeHelpers26. In Python, time machine (or the older freezegun) does the same27.
Example: "ready tomorrow" on a Saturday night
Cogwell shows "ready tomorrow" when a repair will finish the next opening day. A test written on a Tuesday passed for months and failed every Saturday evening, because Sunday is closed.
test "a repair finishing after closing on Saturday is ready on Monday" do
travel_to Time.zone.local(2024, 6, 22, 17, 30) do # Saturday, 5.30pm
card = job_cards(:new_chain)
assert_equal Date.new(2024, 6, 24), card.ready_on
end
end
import time_machine
@time_machine.travel("2024-06-22 17:30 +01:00", tick=False) # Saturday, 5.30pm BST
def test_repair_finishing_after_closing_on_saturday_is_ready_on_monday():
card = JobCardFactory.build(labour_minutes=60)
assert card.ready_on() == date(2024, 6, 24)
Every test that touches "today", "now" or a deadline should set the clock. A test that does not is a test that depends on when you run it.
Cause 3: shared state
One test changes something that outlives it, and another test reads it. Class level variables, a global configuration toggled in one test, a cache, a file in a fixed location, environment variables.
The database is usually safe, thanks to the transactions above. The cache is the classic leak. Rails 7.1 sets the test cache store to :null_store, which stores nothing11, so a test that needs caching switches it on and must switch it back. Django's local memory cache keeps values across tests in the same process, so the fix is to clear it around every test.
Example: the day totals cache
# conftest.py
import pytest
from django.core.cache import cache
@pytest.fixture(autouse=True)
def empty_cache():
cache.clear() # every test starts with an empty cache
yield
cache.clear()
# test/models/day_totals_test.rb
setup do
@previous_cache = Rails.cache
Rails.cache = ActiveSupport::Cache::MemoryStore.new
end
teardown { Rails.cache = @previous_cache } # put back what was there before
This was the shared state behind Owen's PARALLEL_WORKERS=1. With the cache reset in place, the Rails suite went back to two workers.
Cause 4: order dependence
A test passes only when another test ran before it, or fails only when one did. Running tests in random order exposes this, and both frameworks do it. Rails runs test methods in random order9. Minitest prints the seed at the top of every run, for example Run options: --seed 4242, and bin/rails test --seed 4242 replays exactly that order9. Django's runner has --shuffle [SEED], which prints the seed and repeats an order when you pass it back19. In pytest, the pytest randomly plugin shuffles the order and prints Using --randomly-seed=..., which you pass back to reproduce28.
Example: reproducing an order failure
# Rails: the failing CI run printed "Run options: --seed 4242"
bin/rails test --seed 4242
# Django with pytest: the failing run printed "Using --randomly-seed=1553614239"
pytest --randomly-seed=1553614239 -p no:xdist # one process, same order
Copy the seed from the failing CI log, reproduce on a laptop, then remove tests from the run until the pair is left. That pair shows you the shared state.
Cause 5: external services
A test that calls the real SMS provider, the real postcode lookup or the real payment sandbox fails when that service is slow, down or rate limiting. It also sends real messages from CI, which nobody wants.
The fix is to make real network access impossible in tests, so every external call has to be stubbed on purpose. In Ruby, WebMock's WebMock.disable_net_connect!(allow_localhost: true) raises an error on any real HTTP request except to the local machine, which the browser and its driver need29. In Python, pytest socket's --allow-hosts option lets connections reach only the hosts you list30, which is why Cogwell's configuration lists the local addresses. The responses library then stubs the HTTP calls you do want.
Example: the "your bike is ready" text
# test/test_helper.rb
require "webmock/minitest"
WebMock.disable_net_connect!(allow_localhost: true)
# test/jobs/ready_sms_job_test.rb
test "sends one text to the customer" do
stub = stub_request(:post, "https://sms.example/v1/messages").to_return(status: 202)
ReadySmsJob.perform_now(job_cards(:new_chain).id)
assert_requested stub, times: 1
end
# notifications/tests/test_ready_sms.py
import pytest
import responses
from notifications.tasks import send_ready_sms
@pytest.mark.django_db
@responses.activate
def test_sends_one_text_to_the_customer(job_card):
responses.post("https://sms.example/v1/messages", status=202)
send_ready_sms(job_card.pk)
assert len(responses.calls) == 1
Whether the stub still matches the real service is a different question. Fowler suggests contract tests that run against the real service periodically, outside the main pipeline24. A nightly job is a good home for them.
Cause 6: randomness
Factories often fill fields with random values. Sooner or later two random email addresses collide with a unique constraint, or a random price of zero breaks a calculation. The failure is real, but it appears once in 500 runs and cannot be reproduced.
The fix is to make randomness repeatable. Minitest seeds Ruby's random number generator with the run's seed, so --seed replays random data as well as order. pytest randomly resets Python's random, factory boy's and Faker's random state at the start of every test, from the printed seed28. And where a field must be unique, use a sequence, not a random value.
Example: the customer email that collided
# customers/tests/factories.py
import factory
class CustomerFactory(factory.django.DjangoModelFactory):
class Meta:
model = "customers.Customer"
# Was factory.Faker("email"): random, and once in a while a duplicate.
email = factory.Sequence(lambda n: f"customer{n}@cogwellcycles.example")
Quarantine, fix, and why a rerun is a diagnosis, never a cure
Knowing the causes is half of it. The other half is what the team does on the day a test turns out to be flaky. Without a policy, the default is the rerun button, and that is how a suite drifts to 34% red precision.
Google describes a tool that quarantines tests whose flakiness is too high: it takes the test off the critical path and files a bug for developers23. Fowler recommends the same, with a limit on the size of the quarantine so it does not become a graveyard24. The policy I recommend, in five lines:
- A flaky test is a bug, with an owner and a ticket. Not "the board test is like that".
- Quarantine within one working day. The test leaves the gate, so red means something again, and it keeps running elsewhere, so it is not forgotten.
- The quarantine has a limit. At most five tests, and none older than ten working days. Past that, the test is fixed, or deleted and replaced by a better one.
- Rerun to classify, never to pass. Running the test 50 times on the same commit tells you whether it is flaky and how often. A green rerun on the gate tells you nothing about the code.
- Every red build on
maingets one line in a red log: date, test, real or flaky, cause. Red precision falls out of that log for free.
Why a rerun is not a cure: if a test fails once and passes on the second try, either the code has a timing bug that customers can also hit, or the test has one. A rerun cannot tell which. It just picks the outcome you wanted. pytest rerunfailures can retry failed tests automatically31, which is useful in a nightly job that measures flakiness. On the deploy gate it hides exactly the kind of failure the VAT bug hid behind.
Example: quarantining the workshop board test
In Rails, Minitest has no tags, so Cogwell uses a small helper:
# test/support/quarantine.rb
module Quarantine
# Skips the test on the gate, runs it in the nightly flakiness job.
def quarantine!(ticket)
skip "Quarantined, see #{ticket}" unless ENV["RUN_QUARANTINED"]
end
end
ActiveSupport::TestCase.include(Quarantine)
# test/system/workshop_board_test.rb
test "a second mechanic sees the card move to ready" do
quarantine!("COG-412")
# ...
end
In pytest, a marker does the same, and the gate already excludes it with -m "not quarantine":
@pytest.mark.e2e
@pytest.mark.quarantine # COG-412, owner Priya, added 18 June 2024
def test_second_mechanic_sees_card_move_to_ready(page, live_server):
...
The diagnosis is a loop on the same commit:
# Rails: run one test 50 times, count the failures
for i in $(seq 50); do
RUN_QUARANTINED=1 bin/rails test test/system/workshop_board_test.rb:14 > /dev/null || echo FAIL
done | grep -c FAIL
# Django: the same with pytest, in one process, in a fixed order
for i in $(seq 50); do
pytest -m quarantine -k second_mechanic -p no:randomly -q > /dev/null || echo FAIL
done | grep -c FAIL
Three failures in 50 on Cogwell's Rails version. The trace from Playwright and the screenshot from Rails both show the same thing: the second browser session had not finished connecting to the Action Cable or WebSocket channel when the first one clicked. The fix was to wait for the board's "connected" marker before clicking, in both versions. Zero failures in 200 runs afterwards, and the test came out of quarantine after four days.
Coverage as a signal, not a target
Code coverage measures which lines (and, if you ask, which branches) ran during the tests. SimpleCov does it for Ruby32, coverage.py for Python, usually through pytest cov33.
Fowler's 2012 note puts its use in one line: "Test coverage is a useful tool for finding untested parts of a codebase."34 As a number it says little about how good the tests are, and a 100% target tends to produce tests written for the number. So I use it in three ways, none of them a target:
- Read the uncovered lines in the files a change touched. That is where the missing test usually is.
- Set a floor a little below today's figure, so coverage cannot quietly fall. SimpleCov's
minimum_coverageand coverage.py'sfail_underboth fail the run below a threshold32 33. - Turn on branch coverage. An
ifwithout anelsethat is never false shows up only there.
Example: coverage in both versions
# test/test_helper.rb (at the very top, before Rails loads)
require "simplecov"
SimpleCov.start "rails" do
enable_coverage :branch
minimum_coverage line: 88, branch: 75 # a floor, a little below today
end
# Each parallel worker needs its own name, or the results overwrite each other.
class ActiveSupport::TestCase
parallelize_setup { |worker| SimpleCov.command_name "#{SimpleCov.command_name}-#{worker}" }
parallelize_teardown { |_worker| SimpleCov.result }
end
SimpleCov's README explains why the unique name per process matters: parallel processes otherwise overwrite each other's results32.
# pyproject.toml (extract)
[tool.coverage.run]
branch = true
source = ["bookings", "repairs", "parts", "customers", "invoicing", "reporting"]
[tool.coverage.report]
fail_under = 88
show_missing = true
pytest cov combines the results of xdist workers by itself33. Cogwell measures coverage in the unit job only. The browser tests add little line coverage for a lot of time.
Gate the deploy on green, and define "done"
A suite that nobody is obliged to wait for is advice, not a gate. Two settings make it binding.
- Required status checks. In GitHub, a branch protection rule on
maincan require named checks to pass before a pull request can be merged35. Cogwell requires the unit job and both browser jobs. - Deploy only from green
main. Theneedsline in both workflows above. Nobody deploys from a laptop.
Then write down what "done" means, so the gate is part of the work and not an afterthought.
Example: Cogwell's definition of done
| A change is done when | Checked by |
|---|---|
| It has tests that failed before the change and pass after it | the reviewer |
| The right test level was chosen: unit or request first, browser only if the switch off test says so | the reviewer |
| The pipeline is green on the pull request, with no rerun | branch protection |
| No new test is quarantined, and the quarantine is within its limit | the red log |
| Coverage did not fall below the floor | SimpleCov or coverage.py |
It is merged and deployed from main, and the health check passed | the deploy job |
The second row is where most suites are won or lost. A team that writes the right test at the right level never needs a speed project.
Putting it together: 19 and 22 minutes down to under seven
Here is what each change saved on Cogwell's two suites, in the order the team made them. These numbers are illustrative for the invented example. Each step is explained in the sections above, and the order is the order I would recommend: low effort and certain first.
Example: the arithmetic behind the two charts
Rails starts at 19.0 minutes: 3.0 of setup, 7.0 for the 1,412 tests without a browser on one process, 9.0 for the 38 system tests. Gem caching cuts setup to 1.0 (17.0). Two workers, with the cache leak fixed, bring 7.0 down to 3.6 (13.6). 24 system tests at about 14 seconds each take 5.7 minutes instead of 9.0 (10.3). The slowest tests fixed save 1.3 (9.0). Then the unit job (1.0 setup plus 2.8 tests) and two system machines (1.2 setup plus 2.6 tests each) run at the same time, and with a little queueing the last finishes after about 4.5 minutes.
Django starts at 22.0 minutes: 3.5 of setup, 8.5 for the 1,346 tests without a browser, 10.0 for the 34 end to end tests. Caching saves 2.0, the fast hasher 2.0, two xdist workers 3.1, the 12 moved browser tests 3.5, the slowest tests 1.4, and three jobs at the same time leave about 5.0.
Notice what did not happen: no bigger machines, no new CI service, no rewrite. About half the saving came from removing work, not from doing it faster.
And trust: with the 12 flaky tests fixed or in quarantine, the Rails red log for the following month showed nine red builds on main, eight of them real. Red precision went from about 34% to about 89%.
For the person paying for this
You do not need to read a test to judge whether a developer's tests protect your business. My view: ask these questions of anyone who builds an application for you, and expect numbers or a clear habit in return.
| Ask | A good answer sounds like |
|---|---|
| How long from a push to a green or red result? | a number, under ten minutes, and a plan if it is creeping up |
| How many red builds last month were false alarms? | a number from a red log, small |
| What happens when a test turns out to be flaky? | quarantine within a day, an owner, a limit, a fix |
| Can code reach production with a red build? | no, because branch protection and the deploy job make it impossible |
| Who can override that, and when was it last done? | one named person, rarely, and you can say when |
| How many browser tests, and why those? | a short list of real customer journeys |
| What is the coverage trend? | stable or rising, used to find gaps, not chased as a target |
| Show me the last red build and what it caught | a real bug, found before a customer did |
If the answers are vague, the suite is probably not answering either. That is the kind of question I go through in web application development: I write the tests first, the pipeline gates every deploy, and the code, the accounts and the data stay yours.
The checklist: one page for the whole testing series
This is the page to print. Each line links the chapter where it is explained.
| Area | Do this | Where it is explained |
|---|---|---|
| The map | Know your test types and the shape you want before you write tests | The testing map |
| TDD in Rails | Red, green, refactor in small steps, Minitest or RSpec, fixtures or factories by choice | TDD in Rails |
| BDD and browser tests in Rails | System tests that wait, Cucumber only where business people read it | BDD and end to end in Rails |
| TDD in Django | pytest with pytest django, factory boy, the same red, green, refactor | TDD in Django |
| BDD and browser tests in Django | Playwright with auto waiting, the live server transaction trap | BDD and end to end in Django |
| CI | One workflow, services only if tests use them, dependency cache, artefacts on failure | this chapter |
| Speed | Profile first, parallel workers, split machines, fewer browser tests, lean test data | this chapter |
| Trust | Random order with a printed seed, clock set in tests, network blocked, quarantine policy, red log | this chapter |
| Coverage | Branch coverage on, a floor not a target, read the uncovered lines in changed files | this chapter |
| Gate | Required checks on main, deploy only from green, a written definition of done | this chapter |
| Growth | Keep the suite under ten minutes as the code grows | Growing a Rails application and growing a Django project |
If you are starting a project and want this from the first commit, the free workshop is the easiest place to begin: I bring the checklist, you bring the plan.
Conclusion
A test suite answers one question on every push: is it safe to ship? It has to answer fast and answer right, and both can be measured: time to answer, and red precision.
Speed comes mostly from removal. Profile first, cache dependencies, run parallel workers, split across machines only as far as the formula says it pays, and move every browser test that would pass without JavaScript down to a request test.
Trust comes from treating flakiness as a bug. Twelve tests that each flake 2% of the time make one build in five red for no reason. Set the clock, block the network, run in random order with a printed seed, reset shared state, and quarantine with a limit. Rerun to diagnose, never to pass.
Cogwell's two suites went from 19 and 22 minutes to about four and a half and five, and from "always red anyway" to a red that people stop for. Neither framework made the difference. Habits did, and they are the same in Rails and in Django. That is where this programme ends: two good frameworks, one example built twice, and a suite in each that the team can trust.
