TDD, BDD and end to end tests: the testing map for web applications
TL;DR
Difficulty: Beginner
TDD, BDD and end to end are not rival kinds of test. They answer three different questions.
- TDD answers when: write the test first, red, green, refactor. It is for design feedback and confidence, not coverage.
- BDD answers what: agree concrete examples with the business (the three amigos, example mapping), written as Given When Then.
- End to end answers how far: a real browser through the whole system. Keep these few; they are slow and flaky.
- For server rendered Rails and Django, make request tests the thick middle, put every test at the lowest level where its bug can happen, keep every test double honest, and use coverage as a torch, not a target.
What to read first
Developers argue about TDD, BDD and end to end tests as if they were rival camps. They are not: they answer three different questions. This chapter explains each from its original source, shows how they fit together as two loops, and works out, test by test, how much of each a Sheffield bicycle repair chain's booking feature needs.
The question behind this chapter
Ask three developers how they test a web application and you will hear three words used as if they were rivals: TDD, BDD and end to end. One swears by test driven development. One says behaviour driven development is the grown up version. The third says none of that matters, only tests that click through a real browser prove anything. A founder listening in hears an argument about religion and quietly decides testing is something the developers will sort out among themselves.
That is a shame, because the argument is mostly a misunderstanding. This chapter answers one question: what are TDD, BDD and end to end tests, how do they fit together, and how much of each does a web application actually need?
It is the first chapter of the testing series and it is framework neutral. Everything here applies to Ruby on Rails and to Django in the same way, and where the tools differ I name both. The next four chapters go into each framework's toolchain in detail. Everything is written as of Rails 7.1 and Django 5.0, the current releases in May 2024. If you have not read the opening chapter of the programme, Django or Rails: two answers to the same question, it is a good place to start, but you do not need it to follow this one.
Example: the argument at Cogwell Cycles
The programme follows one invented business. Cogwell Cycles is a chain of six bicycle repair workshops in Sheffield (cogwellcycles.example), founded by Hannah. It has 38 mechanics, about 1,150 repair bookings a week, 9,000 active customers and 2,400 spare parts in stock. It is replacing spreadsheets and a rented booking widget with its own web application: online booking with a time slot per mechanic, a live workshop board where job cards move from "waiting" to "in repair" to "ready", parts stock with a nightly reorder report, "your bike is ready" messages by email and SMS, invoices with VAT, and a back office for managers.
Its two developers built the core twice, once in Rails and once in Django, before choosing Rails for the product, as the decision chapter explains. Priya has four years of Python. Owen has three years of TypeScript and React. In the week they started on the real product, they had their first proper disagreement. Priya wanted every rule tested first, in small unit tests. Owen wanted a handful of browser tests that booked a repair the way a customer would, because "that is the only thing Hannah cares about". Hannah asked the reasonable question: "Which of you is right, and how much testing am I paying for?"
Both were right about something, and the rest of this chapter is the answer they arrived at. The business and the people are made up. The code is real and runs on Rails 7.1 and Django 5.0.
Three words, three different questions
Here is the idea that dissolves most of the argument, and it is not one you will find stated like this in the official guides.
TDD, BDD and end to end are not three kinds of test. They answer three different questions.
- Test driven development (TDD) answers "when do I write the test?" Before the code, one small test at a time. It is a working habit, a rhythm. It says nothing about how big the test is.
- Behaviour driven development (BDD) answers "what should I test?" The behaviour the business needs, discovered in a conversation and written down as concrete examples. It is a way of deciding, before anyone writes code.
- End to end answers "how much of the system does this test touch?" All of it: a real browser, the web server, the application, the database. It is a distance, a scope. It says nothing about when you wrote it or where the idea came from.
In one line: TDD is a rhythm, BDD is a conversation, end to end is a distance. Because they sit on different axes, they cannot compete. You can write an end to end test first (that is how BDD usually starts), and you can write a tiny unit test after the code (that is not TDD, but it is still a unit test). Most arguments about "TDD versus end to end" are two people answering different questions and wondering why the other one is wrong.
Even the names of test types are slippery. Simon Stewart of Google described the problem in 2010: teams use "integration test" or "system test" for different things, and he called them "two teams separated by a common jargon"1. So in this chapter I define every test type by what it touches, not by its label, and I give the Rails and Django names side by side.
Example: one sentence from Hannah, seen three ways
Hannah says: "A customer must never be able to book a mechanic who is already booked for that slot."
- The BDD question, what should be tested? The three of them turn the sentence into concrete examples. Two customers want Asha at 9am on Saturday. The first one gets her, the second one sees "This slot has just been taken" and is offered 9.30am. That example is now the specification.
- The TDD question, when is the test written? Priya writes a failing test for "a second booking for the same mechanic and slot is rejected" before there is any code that rejects it. Then she makes it pass.
- The end to end question, how far does the test reach? Owen writes one browser test where a customer picks a slot that was taken a moment earlier and sees the message. It touches everything.
Same rule, three tests, no contradiction. The real questions are which of those tests Cogwell needs, at which level, and how many. That is what the rest of the chapter works out.
Test driven development: red, green, refactor
Kent Beck described TDD in Test Driven Development: By Example, published in November 20022. The cycle has three steps, named after the colours a test runner shows.
- Red. Write a small test for the next bit of behaviour you want. Run it. Watch it fail. The failure proves the test can fail, which is the only evidence that it tests anything at all.
- Green. Write the simplest code that makes the test pass. Not the elegant version, the one that works.
- Refactor. With the test green, clean up the code and the test: remove duplication, improve names, simplify. Run the tests after each change.
Then repeat, one small step at a time. In December 2023 Beck wrote down what he calls "Canon TDD", because he kept seeing the name used for things he did not mean3. It adds a step at the front that most summaries skip: write a list of the test scenarios you want to cover, then turn exactly one item into a real, runnable test, make it (and every earlier test) pass, optionally refactor, and go back to the list until it is empty. He also names common mistakes: mixing refactoring into the step of making a test pass, copying the actual output of the code into the expected value of the test, and removing assertions so a test goes green.
What TDD is for
TDD is often sold as a way to get high test coverage. That is a side effect, not the point. It gives you two things.
- Design feedback. A test is the first user of your code. If the test is hard to write, because you need to build half the application just to call one method, the code is telling you it is tangled. You hear that while the code is still easy to change, not three months later.
- Confidence to change things. A suite built test first covers behaviour you decided on, one piece at a time. When you refactor later, it tells you within seconds whether you broke something you meant.
It is fair to add that TDD has serious critics. In April 2014 David Heinemeier Hansson, the creator of Rails, wrote "TDD is dead. Long live testing.", arguing that strict test first unit testing had pushed Rails developers towards needlessly complex designs, and that he leaned more on tests at the system level4. Martin Fowler, Kent Beck and he then held five recorded conversations, "Is TDD Dead?", in May and June 20145. They disagreed about whether TDD damages design, and agreed on the thing that matters most: self testing code, code that comes with tests that tell you when it breaks, is extremely valuable, and TDD is one way to get it, not the only one.
My view: I write tests first, and I use BDD with Cucumber on the Rails applications and online shops I build. Not because a ritual demands it, but because the moment before the code exists is the least expensive moment to find out what I actually mean. Test first matters most for rules with real logic: prices, VAT, slots, permissions. For a page that just lists records, a test written straight after the code is fine. Insisting on test first for every line of glue code is where the criticism from 2014 lands, and it is fair criticism.
Example: the double booking rule, test first
Priya starts with the list, in a comment at the top of the test file:
# Booking rules to cover (the Canon TDD list)
# * a mechanic cannot be booked twice for the same slot
# * a different mechanic at the same time is fine
# * the same mechanic at a different time is fine
# * bookings close two hours before the slot starts
The last rule is one Hannah adds in the conversation in the next section. Priya takes the first item and writes it as a Rails model test. It creates the records it needs directly, so it runs without any other setup:
# test/models/booking_test.rb
require "test_helper"
class BookingTest < ActiveSupport::TestCase
test "a mechanic cannot be booked twice for the same slot" do
workshop = Workshop.create!(name: "Kelham Island")
asha = Mechanic.create!(workshop: workshop, name: "Asha")
starts = Time.zone.parse("2024-05-25 09:00")
Booking.create!(mechanic: asha, customer: Customer.create!(name: "Sam", email: "sam@example.com"), starts_at: starts)
second = Booking.new(mechanic: asha, customer: Customer.create!(name: "Lee", email: "lee@example.com"), starts_at: starts)
assert_not second.valid?
assert_includes second.errors[:starts_at], "has already been booked"
end
end
She runs bin/rails test test/models/booking_test.rb. Red: the second booking is valid, because nothing forbids it. Now the simplest code that makes it pass:
# app/models/booking.rb
class Booking < ApplicationRecord
belongs_to :mechanic
belongs_to :customer
validates :starts_at, uniqueness: { scope: :mechanic_id, message: "has already been booked" }
end
Green. Then the refactor step, and this is where the design feedback arrives. The Rails validations guide warns that a uniqueness validation alone does not create a database constraint, so two connections can still save two records with the same values, and it recommends a unique index6. Cogwell's Saturday peak makes that real: 30% of the week's online bookings arrive between Friday 6pm and Saturday noon, about 345 bookings in 18 hours. Two customers picking the same popular slot within the same second is not a theoretical case. So the refactor adds the index in a migration (the Active Record chapter covers indexes and constraints in depth):
# db/migrate/20240521090000_add_unique_slot_index_to_bookings.rb
class AddUniqueSlotIndexToBookings < ActiveRecord::Migration[7.1]
def change
add_index :bookings, [:mechanic_id, :starts_at], unique: true
end
end
The Django version of the spike reaches the same place by a slightly different road, as the Django ORM chapter shows. Django 5.0 checks a UniqueConstraint declared on the model when you call full_clean(), and the same constraint exists in the database7. The model and its test:
# bookings/models.py
from django.db import models
class Booking(models.Model):
mechanic = models.ForeignKey("workshops.Mechanic", on_delete=models.PROTECT)
customer = models.ForeignKey("accounts.Customer", on_delete=models.PROTECT)
starts_at = models.DateTimeField()
class Meta:
constraints = [
# One booking per mechanic per slot, enforced by the database too
models.UniqueConstraint(fields=["mechanic", "starts_at"], name="one_booking_per_mechanic_slot"),
]
# bookings/tests/test_models.py
from datetime import datetime, timezone
from django.core.exceptions import ValidationError
from django.test import TestCase
from accounts.models import Customer
from bookings.models import Booking
from workshops.models import Mechanic, Workshop
class BookingTests(TestCase):
def test_mechanic_cannot_be_booked_twice_for_same_slot(self):
workshop = Workshop.objects.create(name="Kelham Island")
asha = Mechanic.objects.create(workshop=workshop, name="Asha")
starts = datetime(2024, 5, 25, 9, 0, tzinfo=timezone.utc)
Booking.objects.create(mechanic=asha, customer=Customer.objects.create(name="Sam", email="sam@example.com"), starts_at=starts)
second = Booking(mechanic=asha, customer=Customer.objects.create(name="Lee", email="lee@example.com"), starts_at=starts)
with self.assertRaises(ValidationError):
second.full_clean()
Notice what the test first habit bought here. The first green test was honest about the rule, and the refactor step, done with a passing test as a safety net, raised the question the test could not answer on its own: what happens when two requests arrive together? That is TDD doing its real job, which is design feedback. Coverage did not come into it.
Behaviour driven development: start with a conversation
Dan North introduced BDD in an article that first appeared in Better Software magazine in March 20068. He had been teaching TDD and kept meeting the same confusion: where to start, what to test, what to call a test. His answer started with one word. He found that people's misunderstandings about TDD "almost always came back to the word test"8, and that thinking in behaviour instead made most of those questions disappear. A test name becomes a sentence describing the next behaviour you care about.
Then he and the business analyst Chris Matts took the idea one level up, from code to requirements. A story's behaviour is its acceptance criteria, and they wrote acceptance criteria as scenarios in a fixed shape8:
- Given some initial context,
- When an event occurs,
- Then ensure some outcomes.
Martin Fowler points out that this is the same structure as the four phase test from Gerard Meszaros, and close to the arrange, act, assert pattern from Bill Wake: set up, do the thing, check the result9. The difference is the audience. Given When Then is written so a business person can read it, argue with it and sign it off.
Gherkin, the language the scenarios are written in
Cucumber, the most widely used BDD tool, reads scenarios written in a small structured language called Gherkin. Its reference defines the keywords: Feature, Rule, Scenario (or Example), Given, When, Then, And, But, Background and Scenario Outline with Examples10. It is precise about what each step is for. A Given puts the system in a known state. A When is an action or an event. A Then checks an outcome that is observable from the outside, such as a page or a message, and not hidden internal state such as a database record10. That last rule is the one most teams break, and it matters, because a scenario that checks the database is a model test wearing a costume.
Gherkin is optional. BDD is the conversation, not the syntax. Rails teams often use Cucumber, and Django teams have behave and pytest bdd. Both work from Gherkin files. But you can practise BDD perfectly well by writing the agreed examples straight into ordinary tests.
The three amigos and example mapping
The conversation has a name. Cucumber's documentation calls it the three amigos: at least three voices, a product owner who decides the scope, a tester who looks for the ways it might break, and a developer who sees what it takes to build11. It need not be three people and it need not happen once; it happens per story, before the work starts.
The most practical technique for that conversation is example mapping, described by Matt Wynne, the lead of the Cucumber project, in December 201512. You use four colours of index card. A yellow card for the story. Blue cards for the rules. Green cards for the examples that illustrate each rule. Red cards for questions nobody in the room can answer yet. Wynne suggests a well understood story should take "about 25 minutes"12; if it takes longer, the story is too big or too unclear.
Example: twenty five minutes with Hannah
Hannah (the business), Priya (developer) and Owen (playing tester for the day) map the story "A customer books a repair online". After 25 minutes the table looks like this:
| Card | Text |
|---|---|
| Yellow (story) | A customer books a repair online |
| Blue (rule 1) | A mechanic can be booked only once per slot |
| Green | Sam books Asha for 9am Saturday, then Lee tries Asha at 9am and is offered 9.30am |
| Green | Lee books Ben at 9am Saturday while Asha is booked: fine |
| Blue (rule 2) | Online booking closes two hours before the slot |
| Green | At 7.05am Sam cannot book the 9am slot, at 6.55am he can |
| Blue (rule 3) | Cogwell needs an email or a mobile number for "your bike is ready" |
| Green | Booking with only a name is rejected with a clear message |
| Green | Booking with a mobile number and no email is accepted |
| Blue (rule 4) | The customer gets a confirmation email straight away |
| Green | Sam books and receives an email naming the workshop, the mechanic and the time |
| Red (question) | What happens to Saturday's bookings when a mechanic rings in sick? |
The red card is not a failure. It is the most valuable thing on the table: a question that would otherwise have surfaced as a support call in the first month. Hannah takes it away to decide, and it becomes its own story.
Owen then writes two of the examples as Gherkin:
Feature: Book a repair online
Customers book a time slot with a mechanic at one of Cogwell's workshops.
Background:
Given the Kelham Island workshop has mechanics "Asha" and "Ben"
Scenario: Booking a free slot
Given it is Friday 24 May 2024 at 7pm
When Sam books "Asha" for Saturday at 9am
Then Sam sees "You are booked in with Asha on Saturday 25 May at 9am"
And Sam receives a confirmation email
Scenario: The slot was taken a moment ago
Given "Asha" is already booked for Saturday at 9am
When Lee tries to book "Asha" for Saturday at 9am
Then Lee sees "This slot has just been taken"
And Lee is offered "Saturday at 9.30am"
Every Then is something Sam or Lee can see. Nothing checks a database table. Hannah can read the file and say "yes, that is what I want", which is the whole point of writing it this way.
The test types, from the inside out
Now the third question: how much of the system does a test touch? Here are the types a Rails or Django web application uses, ordered from smallest to largest, each defined by what it touches. Google's test sizes are a useful yardstick: a small test needs no network and no database, a medium one may use a database and localhost, a large one may use anything1.
| Type | What it touches | Typical speed | Rails 7.1 | Django 5.0 |
|---|---|---|---|---|
| Unit | One class or function, no database | Under a millisecond | ActiveSupport::TestCase on a plain Ruby object | SimpleTestCase or a plain test function |
| Model (integration with the database) | A model and the real test database | A few milliseconds | ActiveSupport::TestCase, in a rolled back transaction | TestCase, in a rolled back transaction |
| Request (controller) | Routing, middleware, controller or view, template, database; no browser | Tens of milliseconds | ActionDispatch::IntegrationTest | The test Client inside TestCase |
| Component | One partial or UI component rendered on its own | Milliseconds | View or component tests, if you use components | Rendering one template with a given context |
| System, end to end | A real browser driving the running application | Seconds | ApplicationSystemTestCase with Capybara and Selenium | StaticLiveServerTestCase with Selenium or Playwright |
| Contract | The agreement between your code and a service you do not run | Varies, often run separately | Any of the above against a recorded or sandbox service | The same |
A few notes from the sources, because the details decide how you use them.
- Both frameworks wrap each database test in a transaction that is rolled back afterwards, which is why model and request tests are fast enough to run by the hundred. The Rails guide says so directly13, and Django's
TestCasedoes the same, which is why it is the common choice14. - Rails calls its request level tests integration tests. The guide describes them as testing how various parts of the application interact, and its functional tests for controllers now inherit from the same class13. Django's test client "is not intended to be a replacement for Selenium"14: it checks that the right template got the right context, and a browser tool checks the rendered HTML and JavaScript.
- Rails system tests run in a real browser through Selenium, with Chrome as the default, and
bin/rails testdeliberately does not run them because they can be slow, and you run them withbin/rails test:system13. Django'sLiveServerTestCasestarts a real server in a background thread for the same purpose14. - A contract test, in Martin Fowler's definition, checks that the test doubles you use for an external service still behave like the real service, and usually runs separately from the main build, often once a day15.
Example: where each type would catch a Cogwell bug
| The bug | The smallest test that catches it |
|---|---|
| VAT on a parts invoice calculated wrongly | Unit test of the invoice calculation |
| Two bookings saved for Asha at 9am | Model test against the real database, with the unique index |
| The booking form posts to the wrong address, or a mechanic can open the manager's report | Request test |
| The job card partial shows "in repair" in the wrong colour | Component test, or simply a request test that checks the HTML |
| The workshop board does not move the card until someone reloads the page | System test in a real browser |
| The SMS provider changed its required phone number format | Contract test |
Read the right hand column from top to bottom and you have the honest answer to "are browser tests worth it?". Yes, for exactly the bugs that only exist in a browser. For everything else, a smaller test catches the same bug faster and tells you more precisely where it is.
Pyramid, trophy and honeycomb: three shapes for three contexts
How many tests of each type? Three well known shapes give three answers. Each was drawn for a particular kind of software, and that context is the part people forget to quote.
The test pyramid. Mike Cohn described the test automation pyramid in his 2009 book Succeeding with Agile16, in three layers: many unit tests at the bottom, fewer service tests in the middle, very few tests through the user interface at the top. Martin Fowler's 2012 summary explains why: tests through the user interface are brittle, expensive to write and slow to run17. Ham Vocke's long article on Fowler's site in 2018 boils the pyramid down to two rules: write tests at different levels of granularity, and the higher the level, the fewer tests you should have18. The pyramid was drawn in a world of desktop and early web applications where user interface automation really was fragile.
The testing trophy. Kent C. Dodds, writing about JavaScript front ends, proposed a trophy shape: static analysis at the base, a modest layer of unit tests, the largest layer of integration tests, and a small cap of end to end tests19. It grew out of Guillermo Rauch's 2016 advice "Write tests. Not too many. Mostly integration."19, and Dodds' principle that the more your tests resemble the way your software is used, the more confidence they give you. Its context is component based JavaScript, where a unit test of one tiny component proves very little.
The testing honeycomb. André Schaffer of Spotify described a honeycomb for microservices in January 201820. It has very few integrated tests that depend on other services being correct, a few tests of implementation details for genuinely complex internal code, and the bulk as integration tests that start a service with its real database and talk to its API. The reason is specific to microservices: most of the complexity lives in how a small service talks to others, not inside it.
All three agree on the top: keep browser tests few. They disagree about the middle, and the disagreement is explained by the context each was drawn for.
Example: the three shapes held up against Cogwell
Cogwell's application is a server rendered monolith. Pages are HTML produced by Rails or Django, with Hotwire or htmx adding the live parts (the Rails series chapter on Hotwire and the Django series chapter on templates, htmx or an API cover both). It is not a microservice, so the honeycomb's reasoning about service boundaries does not quite apply. It has little client side JavaScript, so the trophy's reasoning about components does not quite apply either. And it is not a desktop application with fragile user interface automation, so the pyramid's strict top is still right but its thin middle is not.
Each shape is a good answer to its own question. None was drawn for this one.
My view: in a server rendered application, the request test is the best value honest test
Here is the rule I use for Rails and Django applications that render HTML on the server, and it is my judgement, not a documented standard.
The thickest layer of the suite sits at the HTTP boundary. A request test sends a real request through routing, middleware, the controller or view, the template and the database, and checks the response a browser would receive. In a server rendered application that response is most of the product: the HTML is the user interface. Yet the request test runs in process, inside a rolled back transaction, with no browser, in tens of milliseconds. It is the least expensive test that checks something a user would actually see. And it is honest: it does not mock the database, the routing or the template, so it cannot pass while the real thing is broken in those places.
Under it, model tests carry the rules that need the database to be true (constraints, queries, scopes), and plain unit tests carry pure logic such as VAT and pricing. Over it, a thin layer of browser tests covers only what needs a browser: JavaScript behaviour, live updates, and the one or two journeys that earn money. On the side, a handful of contract tests watch the services you do not run.
Call it a pyramid with a thick waist, or a trophy without the JavaScript. The shape matters less than the reason: put each test at the lowest level where the bug it guards against can actually happen. Vocke makes the same point from the other direction: push tests as far down as you can, and delete higher level tests that add nothing beyond the lower ones18.
Example: a healthy first year suite for Cogwell, in numbers
Here is an illustrative suite for Cogwell's first version, about 1,000 tests. The counts and per test times are my estimates for an application of this size, labelled as such. Your own runner will tell you the real figures.
| Type | Count | Typical time per test | Time for all of them |
|---|---|---|---|
| Unit and model | 600 | 0.02 s | 12 s |
| Request | 350 | 0.06 s | 21 s |
| System (browser) | 40 | 3 s | 120 s |
| Contract | 10 | 0.5 s | 5 s |
| Total | 1,000 | 158 s |
The total time of a suite run on one machine is the sum over the test types of count times time per test, divided by the number of parallel workers:
where is the wall clock time of the run, is the number of tests of type , is the average time of one test of type , and is the number of parallel workers. Foundations: ratios and rates
Worked through: seconds. Both frameworks can run tests in parallel: Rails parallelises by default across processes once a run has 50 or more tests13, and Django's test runner has a --parallel option14. With , seconds, ignoring start up time.
Now look at the shares. The 40 browser tests are 4% of the tests and 76% of the time.
This is the chart to show anyone who wants "more end to end tests". Each extra browser test costs about as much time as 50 request tests. Some are worth it. Every one should have to earn its place.
Which level does a test belong to?
The rule "lowest level where the bug can happen" turns into a short sequence of questions you can ask about any example on the map. The order matters: it starts with the expensive cases so that they are rare.
There is a second, faster rule of thumb that falls straight out of example mapping, and I have not seen it written down elsewhere. The colour of the card tells you the level.
- The yellow story gets one browser scenario: the main journey, end to end, so you know the pieces are wired together.
- Each blue rule gets a request test, because a rule is something the application enforces at its boundary, and the request is where a user meets it.
- Each green example gets a fast test at the lowest level that can show it: a model or unit test for the logic, or another case in the request test.
- Each red question gets no test at all until it is answered. A test for an unanswered question is a guess written in code.
It is a starting point, not a law. A rule that only exists in JavaScript moves up, and an example that is pure arithmetic moves down. But it turns a 25 minute conversation into a test list in another five.
Example: the "book a repair" feature, test by test
Here is the complete list Priya and Owen derive from Hannah's map. The level column follows the flow above, and the tools are named for both versions of the spike.
| From the map | Test | Level | Rails 7.1 | Django 5.0 |
|---|---|---|---|---|
| Story | A customer books a free slot and sees the confirmation | System (browser) | Capybara system test, or the Cucumber scenario | Playwright or Selenium test, or the behave scenario |
| Story | The workshop board shows the new booking without a reload | System (browser) | System test | Live server test |
| Rule 1 | Posting a taken slot returns the form with "This slot has just been taken" | Request | ActionDispatch::IntegrationTest | Test Client |
| Rule 1, examples | Same mechanic and slot rejected; other mechanic fine; other time fine | Model | Model test with the unique index | TestCase with UniqueConstraint |
| Rule 1, example | The next free slot offered is 9.30am | Unit | Plain Ruby object for slot finding | Plain function |
| Rule 2 | Posting a slot less than two hours ahead is refused | Request | Integration test with time frozen | Test Client with time fixed |
| Rule 2, examples | 7.05am refused, 6.55am accepted for a 9am slot | Unit | Boundary cases of the cut off rule | Same |
| Rule 3 | Booking without email and mobile shows a clear error | Request | Integration test | Test Client |
| Rule 3, example | Mobile only is accepted | Model | Validation test | full_clean() test |
| Rule 4 | A confirmation email is sent with workshop, mechanic and time | Mailer or email | Mailer test, plus "email enqueued" in the request test | mail.outbox check |
| Red card | Mechanic rings in sick | None yet |
That is 10 tests across four levels for one feature, two of them in a browser. The Gherkin file from the conversation maps onto the first two rows. Everything else is the faster machinery underneath that makes those two scenarios rarely fail for a boring reason. The next four chapters write this exact list in each framework: test driven development in Rails comes next, then BDD and end to end tests in Rails, then the same two chapters for Django.
The habit that ties it together is two loops, one inside the other. The outer loop is BDD: a scenario from the conversation, failing, at the top. The inner loop is TDD: red, green, refactor, at the lowest level that can show each piece. You go round the inner loop many times for each turn of the outer one.
Test doubles: mocks, stubs and fakes, and when they lie
Sometimes a test cannot or should not use the real thing: the SMS provider charges per message, the payment service is slow, the clock moves. You replace it with a test double. Martin Fowler's essay "Mocks Aren't Stubs", last revised in January 2007, uses Gerard Meszaros' names for the kinds21:
- A dummy is passed around but never used, to fill a parameter list.
- A fake works, but takes a shortcut that makes it unfit for production, such as an in memory store.
- A stub returns canned answers to the calls the test makes.
- A spy is a stub that also records how it was called.
- A mock is set up with expectations about which calls it should receive, and fails the test if they do not happen.
Fowler also describes two schools21. Classicist testers use real objects where practical and doubles only when the real thing is awkward. Mockist testers mock any collaborator with interesting behaviour, which supports designing from the outside in but couples the tests more tightly to how the code is built. Both schools are respectable. In a server rendered Rails or Django application, my view is that the classicist style fits better: the database is fast in a transaction, so there is rarely a reason to mock your own models, and a test that mocks them checks your assumptions about your own code rather than your code.
Where doubles lie. A double is a statement about how something else behaves. When the something else changes and the double does not, the test stays green and the product breaks. Doubles lie in three predictable places: at services you do not control, at your own database (a mocked query cannot catch a missing index or a wrong join), and at time (a stubbed clock that never crosses midnight or a daylight saving change).
Example: the SMS fake that said yes
Cogwell sends "your bike is ready" by SMS. In tests, Owen uses a fake SMS client that records each message instead of sending it, and the request test checks that one message was recorded with the right text. It is a good test. It runs in milliseconds and costs nothing.
Then the provider starts rejecting numbers that are not in international format, so "0114 496 0000" fails and "+44 114 496 0000" works. The fake accepts both, so every test stays green while customers stop getting their messages.
Two small fixes, together:
- Make the fake as strict as the real thing. The fake rejects numbers the provider's documentation says it rejects. Now a request test with a local format number fails, and the fix (normalise numbers to international format when the customer saves them) gets a unit test of its own.
- Add a contract test. Once a day, outside the main build, a small test sends one message to the provider's test environment, or checks a recorded response against the provider's current documentation, and fails if the agreement has changed15. It is the only test that talks to the real provider, so it is the only one that can notice the provider changing.
The pattern generalises: every double needs a test that keeps it honest. For your own database the honest test is simply not to double it. For the clock it is a test at the awkward boundaries. For an outside service it is a contract test.
Flaky tests: the tax on every browser test
A flaky test passes and fails on the same code without anything changing. Google reported in 2016 that about 1.5% of all its test runs reported a flaky result, that almost 16% of its tests had some level of flakiness, and that about 84% of the transitions it saw from pass to fail involved a flaky test22. The last number is the expensive one: most red builds were not bugs.
Flakiness grows with scope. A unit test has almost nothing that can vary between runs. A browser test has a browser, a server thread, timing, animations, network requests and the order the page loads things in. The usual cause in Rails and Django system tests is a test that checks the page before the page has finished changing. The tools have an answer: Capybara retries its finders and matchers for a short time before giving up (two seconds by default)23, and Playwright waits for an element to be ready before acting on it24. A fixed sleep in a test is almost always a flaky test waiting to happen.
Example: forty browser tests at a 0.5% flake rate
Suppose each of Cogwell's 40 browser tests is quite reliable: it fails for no reason once in 200 runs, a flake rate of 0.5%. How often is the whole build red with no bug at all? A build is green only if every browser test passes, so
where is the chance that one test fails for no reason in a run, is the number of such tests, and is the chance that all pass, assuming the flakes are independent. Foundations: probability
With and : , so about 18% of builds are red for no reason. Nearly one push in five. Double the browser tests to 80 and it is 33%, and at 160 it is 55%, a coin toss.
This is the quiet reason a suite stops being trusted. Once the team learns that red usually means "run it again", red stops meaning anything, and the one real failure gets rerun too. A few browser tests are worth their tax. Hundreds rarely are. The final chapter of this series is about keeping the rate down in continuous integration (CI), the server that runs the suite on every change.
Coverage is a torch, not a target
Test coverage measures which lines (or branches) of your code ran during the tests. Rails teams usually measure it with the SimpleCov gem, Django teams with coverage.py. It is useful, and the useful part is narrow. Martin Fowler's 2012 note puts it well: coverage helps you find untested code, but it "is of little use as a numeric statement of how good your tests are"25. He adds that a thoughtful suite will probably land somewhere in the upper 80s or 90s, and that he would be suspicious of 100%, because once a number becomes the goal people write tests to hit the number.
Coverage tells you a line ran. It does not tell you that anything checked the result.
Example: 94% and a VAT bug
Cogwell's invoicing module shows 94% coverage. A parts invoice of £40.00 net should carry VAT at the UK standard rate of 20%26, £8.00, for a total of £48.00. A refactor introduces a bug: the total is calculated as net times 0.2 instead of net times 1.2, so the invoice says £8.00.
The existing test created an invoice and asserted that the total was greater than zero. The line with the bug ran, so coverage counted it. £8.00 is greater than zero, so the test passed. Coverage stayed at 94%.
The fix is one assertion on the actual figure: net £40.00, VAT £8.00, total £48.00. Notice that this is also one of Kent Beck's named mistakes in reverse3: a test with an assertion too weak to fail is barely better than no test. Use coverage the other way round: look at the lines it shows as never run, and ask for each one whether a bug there would matter. VAT here is used as a simple sum; for VAT itself rely on HMRC's guidance, and treat this as general information, not tax advice.
How much of each does a web application need?
Back to Hannah's question. Here is the answer Cogwell settled on, and the rule set I would give any team building a server rendered Rails or Django application.
- BDD for every story that has rules. Twenty five minutes of example mapping per story, with the business in the room. The output is the test list. Skip it for stories with no rules ("add a link to the footer").
- TDD for every piece of real logic. Slots, cut off times, VAT, prices, permissions, stock levels: test first, one example at a time. For plain wiring, tests straight after the code are fine.
- Request tests as the thick middle. One for each rule, at the boundary where a user meets it. This is where most of the suite's confidence comes from in a server rendered application.
- Model and unit tests underneath, with the real database, for every green card example that is quicker to show there.
- Browser tests for journeys and JavaScript only. One per story's main journey, plus one for each behaviour that only exists in a browser. Keep them a small share of the count, and watch their share of the time.
- A contract test for every outside service, and a fake that is as strict as the real thing.
- Coverage as a torch, reviewed now and then for gaps, never a gate on a number.
Example: what it means for Cogwell's first six months
With roughly 20 stories in the first version, the rule set gives Cogwell about 20 to 40 browser tests, a few hundred request tests and several hundred model and unit tests, the shape in the chart above. The whole suite runs in well under a minute on four workers, the browser tests stay under one in five false red builds as long as their flake rate stays at or below 0.5%, and every rule Hannah agreed to has a test she could read the name of. Two years later, with 14 workshops and many more features, that suite will have grown well past a thousand tests and its CI time will need attention, which is exactly what the last chapter of the series is about.
For the person paying for this
You do not need to read test code to judge whether a team tests well. Ask these questions, and listen for concrete answers.
| Ask | A good answer sounds like |
|---|---|
| Can I read the scenarios for this feature? | "Yes, here they are, in plain English. You agreed them in the session." |
| What happens when you fix a bug? | "First a test that fails because of the bug, then the fix." |
| How long does the full suite take, and how often is it red for no reason? | A number in minutes, and a flake rate they actually track |
| How many browser tests are there, and why those? | A short list of journeys, each with a reason |
| What is your coverage target? | "Coverage shows the gaps. It is not a number to hit." |
| What happens if the SMS or payment provider changes? | "A contract test tells us, usually before customers notice." |
A team that answers like that is spending your money on tests that protect it. If you are weighing who should build your application, how I build web applications describes how I work, tests first included, and the free workshop is the place to map your first story together.
Conclusion
TDD, BDD and end to end tests are not rival camps. TDD is a rhythm (write the test first, red, green, refactor), BDD is a conversation (agree concrete examples with the business before building), and end to end is a distance (how much of the system a test touches). They fit together as two loops: a BDD scenario on the outside, many small TDD cycles inside it.
How much of each depends on what you are building. The pyramid, the trophy and the honeycomb were each drawn for a different kind of software. For a server rendered Rails or Django application, my view is a suite with a thick middle of request tests, model and unit tests underneath, a thin layer of browser tests for journeys and JavaScript, and a contract test for every outside service. Put every test at the lowest level where its bug can happen, let the colour of the example mapping card suggest the level, keep every double honest, and treat coverage as a torch. Then the suite does what it is for: it tells you the truth quickly, and people believe it.
