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. Freewheel Cycles is a chain of bicycle repair workshops in Limerick (freewheelcycles.example), founded by Niamh. Two years after launch it has 14 workshops, 95 mechanics and about 3,100 repair bookings a week. Aisling and Cian 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).

FactRails versionDjango version
Tests1,4501,380
Browser tests38 system tests34 end to end tests
Time in continuous integration (CI)19 minutes22 minutes
Targetunder 7 minutesunder 7 minutes
Pushes that trigger CI (my assumption)about 20 a dayabout 20 a day

Niamh 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 Cian 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:

  1. One mainline. Everybody's work meets in one branch, usually main, often. Long lived branches postpone the integration problem until it is large.
  2. A self testing build. "It compiles" proves little. The build runs the tests, and a failing test fails the build.
  3. 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.

IdeaGitHub ActionsGitLab 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 machinea joba job
A command inside a joba stepa line under script
A database next to the jobservices with a container image5services with a Docker image4
The same job several timesstrategy.matrix3parallel: N, with CI_NODE_INDEX and CI_NODE_TOTAL set in each copy4
Files kept after the runan artefact via actions/upload-artifact6artifacts
Order between jobsneedsstages 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. Freewheel's code is private, so two cores it is.

Example: Freewheel's pipeline as a flow

Before writing YAML, Aisling 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.

Tap or click to enlarge

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: Freewheel'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/freewheel_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-ruby reads the Ruby version from .ruby-version, and bundler-cache: true runs bundle install and caches the installed gems between runs8. The largest saving in this chapter for the least effort.
  • db:schema:load builds the test database from db/schema.rb instead of replaying two years of migrations.
  • bin/rails test runs every test except system tests. The Rails testing guide says so plainly, because system tests "can be slow"9.
  • --profile 20 lists the 20 slowest tests at the end9, the measurement for the next section.
  • GitHub Actions sets the variable CI on every runner10. The config/environments/test.rb that Rails 7.1 generates contains config.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 Freewheel'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   # Freewheel'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. Freewheel'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: Freewheel'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: freewheel.settings_test
  SECRET_KEY: only-for-ci
  DATABASE_URL: postgres://postgres:postgres@127.0.0.1:5432/freewheel
  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-python with cache: pip caches downloaded packages, keyed on the requirements files13. The pinned requirements.txt comes from pip tools, as set up in starting a new Django project.
  • makemigrations --check --dry-run fails the build when someone changed a model and forgot the migration.
  • -n auto comes 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   # Freewheel'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:

# freewheel/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 = "freewheel.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 Freewheel 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 Freewheel's 20 slowest tests had in common

Aisling 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.

CauseRailsDjangoFix
Browser test that does not need a browser76move it down to a request test
Test data builds far more than the test reads55build less, see the test data section
Password hashing in user factories04a fast hasher in test settings
Photo processing for job cards32in memory storage, no image variants
A real HTTP call that times out22block the network, stub the SMS provider
Genuinely slow, and worth it31keep

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. Freewheel'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:

Twall=Tsetup+max⁡i=1mTiT_{\text{wall}} = T_{\text{setup}} + \max_{i=1}^{m} T_i

  • TwallT_{\text{wall}} is the time from push to result for that stage.
  • TsetupT_{\text{setup}} is what every machine pays before the first test: checkout, cache restore, database, browser.
  • mm is the number of machines.
  • TiT_i is the test time on machine ii. The stage waits for the slowest machine, hence the maximum.

The ideal is Ti=Ttests/mT_i = T_{\text{tests}} / m for every machine. Setup is paid on every machine, so adding machines stops paying when TsetupT_{\text{setup}} approaches the per machine test time. More on ratios like this in Foundations: ratios and rates.

Example: two machines or three for Freewheel's browser tests

After the other fixes below, Freewheel'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: 1.2+5.2=6.41.2 + 5.2 = 6.4 minutes.
  • Two machines, well balanced: 1.2+5.2/2=3.81.2 + 5.2 / 2 = 3.8 minutes.
  • Three machines: 1.2+5.2/3≈2.91.2 + 5.2 / 3 \approx 2.9 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 is grand.

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 1.2+3.4=4.61.2 + 3.4 = 4.6 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 Cian 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 TestCase also wraps each test in a transaction. TransactionTestCase and LiveServerTestCase cannot, 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 the db and transactional_db fixtures, and the live_server fixture 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.

  1. Reuse the test database on your laptop. pytest django's --reuse-db keeps it between runs, --create-db rebuilds it after schema changes15. Django's own runner calls it --keepdb21. In CI there is nothing to reuse, and the option does no harm.
  2. 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-migrations builds 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.
  3. 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 Freewheel'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: Freewheel's 38 system tests, sorted

Cian goes through the 38 Rails system tests with the question. The Django team does the same for its 34, with a similar result.

GroupTests (Rails)Passes without JavaScript?Decision
Booking form validation messages5yesrequest tests
Back office filters and sorting4yesrequest tests
Login redirects for the three roles3yesrequest tests
Invoice download links2yesrequest tests
Full booking journey, customer side4yeskeep, as journey smoke tests
Workshop board, live updates with two sessions6nokeep
Job card photo upload with preview3nokeep
Slot picker5nokeep
Everything else6nokeep

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(:castletroy).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 Freewheel'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 build and build_stubbed for objects that never touch the database. factory boy has Factory.build(). A price calculation does not need a saved row.
  • Make associations lazy or explicit. A JobCardFactory that 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

Freewheel's Django JobCardFactory used SubFactory all the way down. Aisling 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 €52 = €78.00, parts €24.00, subtotal €102.00, VAT 23% = €23.46
    assert card.total_with_vat(usages) == Decimal("125.46")

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 Freewheel'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 Freewheel.

How a small flake rate becomes a red build every few runs

If a suite contains kk flaky tests, and each fails at random with probability ff on a run, independently, then the chance that a run is red for no reason is:

Pnoise=1−(1−f)kP_{\text{noise}} = 1 - (1 - f)^{k}

  • PnoiseP_{\text{noise}} is the probability that at least one flaky test fails on a run.
  • ff is the chance that one flaky test fails on one run.
  • kk is the number of flaky tests in the suite.
  • (1−f)k(1-f)^k 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 bb of runs contain a real bug, red precision, the share of red builds that are real, is:

precision=b1−(1−b)(1−Pnoise)\text{precision} = \frac{b}{1 - (1 - b)(1 - P_{\text{noise}})}

  • bb is the chance that a run contains a real failure, assumed to turn it red. It is the numerator.
  • (1−b)(1−Pnoise)(1-b)(1-P_{\text{noise}}) 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.
  • precision\text{precision} 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 TT to:

E[T]=T1−PnoiseE[T] = \frac{T}{1 - P_{\text{noise}}}

  • TT is the time of one run.
  • 1−Pnoise1 - P_{\text{noise}} is the chance that a run of a correct change comes back green.
  • E[T]E[T] 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 Freewheel's suite

Aisling 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.

  • Pnoise=1−0.9812=1−0.785=0.215P_{\text{noise}} = 1 - 0.98^{12} = 1 - 0.785 = 0.215. About one run in five is red for no reason.
  • Assume one run in ten contains a real failure, b=0.10b = 0.10. Then precision is 0.10/(1−0.90×0.785)=0.10/0.294=0.340.10 / (1 - 0.90 \times 0.785) = 0.10 / 0.294 = 0.34.
  • With T=19T = 19 minutes, E[T]=19/0.785≈24.2E[T] = 19 / 0.785 \approx 24.2 minutes.

Two out of three red builds at Freewheel 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.

Grouped bar chart of flaky test failures by cause in the invented Freewheel example over three months, illustrative numbers. Asynchronous user interface: Rails 11, Django 9. Time and dates: Rails 6, Django 5. Shared state: Rails 5, Django 6. Order dependence: Rails 4, Django 3. External services: Rails 3, Django 4. Randomness: Rails 2, Django 3. Totals: Rails 31, Django 30. Tap or click to enlarge

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

Freewheel 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 Irish Standard Time
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 Cian'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 Eircode 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 Freewheel'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}@freewheelcycles.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:

  1. A flaky test is a bug, with an owner and a ticket. Not "the board test is like that".
  2. 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.
  3. 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.
  4. 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.
  5. Every red build on main gets 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 Freewheel 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!("FWC-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   # FWC-412, owner Aisling, 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 Freewheel'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_coverage and coverage.py's fail_under both fail the run below a threshold32 33.
  • Turn on branch coverage. An if without an else that 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. Freewheel 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.

  1. Required status checks. In GitHub, a branch protection rule on main can require named checks to pass before a pull request can be merged35. Freewheel requires the unit job and both browser jobs.
  2. Deploy only from green main. The needs line 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: Freewheel's definition of done

A change is done whenChecked by
It has tests that failed before the change and pass after itthe reviewer
The right test level was chosen: unit or request first, browser only if the switch off test says sothe reviewer
The pipeline is green on the pull request, with no rerunbranch protection
No new test is quarantined, and the quarantine is within its limitthe red log
Coverage did not fall below the floorSimpleCov or coverage.py
It is merged and deployed from main, and the health check passedthe 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 Freewheel'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.

Waterfall chart of CI wall clock time for the invented Freewheel Rails suite, illustrative numbers. Start 19.0 minutes. Caching gems saves 2.0. Fixing shared state and turning two parallel workers back on saves 3.4. Moving 14 of 38 system tests to request tests saves 3.3. Fixing the slowest tests saves 1.3. Splitting into a unit job and two system test machines that run at the same time saves 4.5. Result 4.5 minutes. Tap or click to enlarge
Waterfall chart of CI wall clock time for the invented Freewheel Django suite, illustrative numbers. Start 22.0 minutes. Caching pip packages saves 2.0. A fast password hasher in test settings saves 2.0. Two pytest xdist workers save 3.1. Moving 12 of 34 end to end tests to request tests saves 3.5. Fixing the slowest tests saves 1.4. Splitting into a unit job and two end to end machines saves 5.0. Result 5.0 minutes. Tap or click to enlarge

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.

AskA 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 caughta 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.

AreaDo thisWhere it is explained
The mapKnow your test types and the shape you want before you write testsThe testing map
TDD in RailsRed, green, refactor in small steps, Minitest or RSpec, fixtures or factories by choiceTDD in Rails
BDD and browser tests in RailsSystem tests that wait, Cucumber only where business people read itBDD and end to end in Rails
TDD in Djangopytest with pytest django, factory boy, the same red, green, refactorTDD in Django
BDD and browser tests in DjangoPlaywright with auto waiting, the live server transaction trapBDD and end to end in Django
CIOne workflow, services only if tests use them, dependency cache, artefacts on failurethis chapter
SpeedProfile first, parallel workers, split machines, fewer browser tests, lean test datathis chapter
TrustRandom order with a printed seed, clock set in tests, network blocked, quarantine policy, red logthis chapter
CoverageBranch coverage on, a floor not a target, read the uncovered lines in changed filesthis chapter
GateRequired checks on main, deploy only from green, a written definition of donethis chapter
GrowthKeep the suite under ten minutes as the code growsGrowing 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.

Freewheel'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.

If your suite is slow or nobody believes it any more, book the free workshop: we look at your pipeline and your red builds together, and the first two weeks of work are on me.

Sources

  1. 1.

    Kent Beck with Cynthia Andres, Extreme Programming Explained: Embrace Change, second edition, Addison Wesley, 2004 (the practice "Ten Minute Build"). https://www.informit.com/store/extreme-programming-explained-embrace-change-9780321278654

  2. 2.

    Martin Fowler, "Continuous Integration", martinfowler.com, first published 10 September 2000, revised 18 January 2024. https://martinfowler.com/articles/continuousIntegration.html

  3. 3.

    GitHub, "Workflow syntax for GitHub Actions" (jobs, needs, strategy.matrix, concurrency, timeout), GitHub Docs, 2024. https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions

  4. 4.

    GitLab, "CI/CD YAML syntax reference" (services, parallel, CI_NODE_INDEX, CI_NODE_TOTAL), GitLab Docs, 2024. https://docs.gitlab.com/ee/ci/yaml/

  5. 5.

    GitHub, "Creating PostgreSQL service containers", GitHub Docs, 2024. https://docs.github.com/en/actions/using-containerized-services/creating-postgresql-service-containers

  6. 6.

    GitHub, "upload artifact" README, version 4, GitHub, 2024. https://github.com/actions/upload-artifact

  7. 7.

    GitHub, "About GitHub hosted runners" (standard runners for private repositories: Linux, 2 processors, 7 GB; ubuntu-latest uses Ubuntu 22.04), GitHub Docs, as of June 2024; and "GitHub hosted runners: double the power for open source", The GitHub Blog, 17 January 2024. https://docs.github.com/en/actions/using-github-hosted-runners/about-github-hosted-runners/about-github-hosted-runners

  8. 8.

    Ruby, "setup ruby" README (bundler-cache), GitHub, 2024. https://github.com/ruby/setup-ruby

  9. 9.

    Rails Core Team, "Testing Rails Applications" (parallel testing, system tests, test runner options including --seed and --profile), Rails Guides for Rails 7.1, 2023. https://guides.rubyonrails.org/v7.1/testing.html

  10. 10.

    GitHub, "Variables: default environment variables" (CI is always set to true), GitHub Docs, 2024. https://docs.github.com/en/actions/learn-github-actions/variables

  11. 11.

    Rails Core Team, generated config/environments/test.rb template, Rails 7.1.3.4 source, GitHub, 2024. https://github.com/rails/rails/blob/v7.1.3.4/railties/lib/rails/generators/rails/app/templates/config/environments/test.rb.tt

  12. 12.

    Rails Core Team, "ActionDispatch::SystemTesting::TestHelpers::ScreenshotHelper", Rails API documentation 7.1. https://api.rubyonrails.org/v7.1/classes/ActionDispatch/SystemTesting/TestHelpers/ScreenshotHelper.html

  13. 13.

    GitHub, "setup python" README, version 5 (caching packages dependencies), GitHub, 2024. https://github.com/actions/setup-python

  14. 14.

    pytest xdist contributors, "Running tests across multiple CPUs", pytest xdist documentation, version 3.6, April 2024. https://pytest-xdist.readthedocs.io/en/stable/distribution.html

  15. 15.

    pytest django contributors, "Database access" (--reuse-db, --create-db, --no-migrations, xdist database suffix), pytest django documentation, version 4.8, January 2024. https://pytest-django.readthedocs.io/en/latest/database.html

  16. 16.

    Jerry Pussinen and contributors, "pytest split" README, version 0.9.0, 19 June 2024. https://github.com/jerry-git/pytest-split

  17. 17.

    Microsoft, "Pytest plugin reference" (--tracing, --screenshot, --output), Playwright for Python documentation, 2024. https://playwright.dev/python/docs/test-runners

  18. 18.

    Django Software Foundation, "Django 5.0 release notes", 4 December 2023. https://docs.djangoproject.com/en/5.0/releases/5.0/

  19. 19.

    Django Software Foundation, "django admin and manage.py: test" (--parallel, --shuffle, --durations, --keepdb), Django 5.0 documentation. https://docs.djangoproject.com/en/5.0/ref/django-admin/

  20. 20.

    Rails Core Team, Active Model railtie (ActiveModel::SecurePassword.min_cost = Rails.env.test?), Rails 7.1.3.4 source, GitHub, 2024. https://github.com/rails/rails/blob/v7.1.3.4/activemodel/lib/active_model/railtie.rb

  21. 21.

    Django Software Foundation, "Writing and running tests" (the test database, order in which tests are executed, speeding up the tests), Django 5.0 documentation. https://docs.djangoproject.com/en/5.0/topics/testing/overview/

  22. 22.

    Rails Core Team, "Ruby on Rails 5.1 Release Notes" (transactional tests now wrap all Active Record connections, including those of extra threads), Rails Guides, 2017. https://guides.rubyonrails.org/v7.1/5_1_release_notes.html

  23. 23.

    John Micco, "Flaky Tests at Google and How We Mitigate Them", Google Testing Blog, 27 May 2016. https://testing.googleblog.com/2016/05/flaky-tests-at-google-and-how-we.html

  24. 24.

    Martin Fowler, "Eradicating Non Determinism in Tests", martinfowler.com, 14 April 2011. https://martinfowler.com/articles/nonDeterminism.html

  25. 25.

    Thomas Walpole and contributors, Capybara README and configuration (default_max_wait_time, default 2 seconds), version 3.40.0, January 2024. https://github.com/teamcapybara/capybara

  26. 26.

    Rails Core Team, "ActiveSupport::Testing::TimeHelpers", Rails API documentation 7.1. https://api.rubyonrails.org/v7.1/classes/ActiveSupport/Testing/TimeHelpers.html

  27. 27.

    Adam Johnson, "time machine" README, version 2.14, March 2024. https://github.com/adamchainz/time-machine

  28. 28.

    Adam Johnson and contributors, "pytest randomly" README, version 3.15.0, August 2023. https://github.com/pytest-dev/pytest-randomly

  29. 29.

    Bartosz Blimke and contributors, "WebMock" README, version 3.23, May 2024. https://github.com/bblimke/webmock

  30. 30.

    Mike Fiedler and contributors, "pytest socket" README, version 0.7.0, January 2024. https://github.com/miketheman/pytest-socket

  31. 31.

    pytest dev contributors, "pytest rerunfailures" README, version 14.0, March 2024. https://github.com/pytest-dev/pytest-rerunfailures

  32. 32.

    SimpleCov contributors, "SimpleCov" README (minimum_coverage, branch coverage, parallel tests and command_name), version 0.22.0. https://github.com/simplecov-ruby/simplecov

  33. 33.

    Ned Batchelder and contributors, "Configuration reference", coverage.py documentation, version 7.5, June 2024; and pytest cov documentation, "Distributed testing (xdist)", version 5.0. https://coverage.readthedocs.io/en/7.5.4/config.html

  34. 34.

    Martin Fowler, "TestCoverage", martinfowler.com, 17 April 2012. https://martinfowler.com/bliki/TestCoverage.html

  35. 35.
Shelter

I’m running the London Marathon for Shelter. Sunday 25 April 2027

My personal fundraiser. Shelter, the National Campaign for Homeless People Limited, registered charity 263710 (England and Wales) and SC002327 (Scotland), registered with the Fundraising Regulator.

Donate to Shelter