BDD and end to end testing in Django: behave, pytest bdd and Playwright

TL;DR

Difficulty: Intermediate

A Django end to end test is three actors at once: your test thread, a live server thread and a browser. Every hard problem sits on a border between two of them.

  • Test data must be committed for the live server to see it. Use transaction=True, request the live server up front, and run browser tests on the same database as production, because SQLite hides the trap.
  • Use Playwright: every action and every expect waits for the page, so you never sleep. Set DJANGO_ALLOW_ASYNC_UNSAFE for the test process only, and open contexts through new_context so traces are recorded.
  • Write a browser test only where it can fail for a reason the test client cannot see: htmx, two people at once, or the page as assembled. The seams belong to the stack, so the same scenario can be a browser test in Rails and a test client test in Django.
  • Use Gherkin when a business person reads it. With pytest, use pytest bdd, keep steps declarative, and bind each scenario to the lowest cost level that can catch its bug.

Browser tests are the only tests that see what your customers see, and the easiest way to build a slow suite nobody trusts. This chapter shows the narrow path between the two in Django 5.0: a model for where flaky tests come from, the database transaction trap, Playwright, pytest bdd or behave, and htmx, worked through on the same booking journey and live workshop board as the Rails chapter, with the same feature file.

The question behind this chapter

"How do I write behaviour driven and end to end tests in Django that catch real bugs without becoming slow and flaky?" Most Django developers have met both halves of the problem. A suite with no browser tests ships a booking page whose button does nothing, because one JavaScript file failed to load. A suite with too many browser tests takes 20 minutes, fails one run in five for no visible reason, and teaches everyone to press "rerun" without reading the error.

This chapter is about the narrow path between the two. I keep using the invented example of this programme: Cogwell Cycles, a chain of six bicycle repair workshops in Sheffield (cogwellcycles.example), founded by Hannah, with two developers, Priya and Owen. In the decision chapter they chose Rails for the product, after building a two week spike of the core in both frameworks. What follows is the Django version of the spike's browser tests. It mirrors the Rails chapter on Cucumber, Capybara and system tests journey for journey: Morgan Fell books Dev at the Kelham Island workshop for next Saturday at 9am, and a Blue Brompton with a puncture moves across the live workshop board. The feature file is the same, word for word.

If you have not read test driven development in Django, start there: this chapter builds on its pytest setup and its factories. The board under test is the one from the front end chapter on templates and htmx. And for where browser tests sit among all the others, the testing map is the overview.

The code is written for Django 5.0, Python 3.12, pytest django 4.8, pytest bdd 7.2, Playwright for Python 1.44 with its pytest plugin 0.5, and htmx 1.9.12, the version the front end chapter uses. htmx 2.0 was released yesterday, on 17 June 20241. I stay on 1.9 here, because a brand new major version is something you upgrade to on purpose, with its own tests, not in the middle of a chapter about tests.

My model: three actors, three borders

Most advice on flaky browser tests is a list: avoid sleeps, use good selectors, reset the database. The list is right, and it is hard to remember because it has no shape. Here is the shape I use.

A Django end to end test is never a single moving part. It is three actors running at the same time:

  1. The test thread. Your pytest code. It creates the data, tells the browser what to do, and checks the result.
  2. The live server thread. A real Django server that the test starts in the background of the same Python process. It answers the browser's requests with its own database connection.
  3. The browser. A separate operating system process (Chromium, Firefox or WebKit) that loads pages, runs htmx and the rest of the JavaScript, and holds the cookies.

Every hard problem in this kind of test lives on a border between two of them:

BorderWhat crosses itThe classic failure
Test thread and live serverData in the database, settings, the email outboxThe server cannot see the rows the test just made: the database transaction trap
Test thread and browserCommands ("click", "fill") and questions ("is this visible?")The test asks before the page has finished changing: a timing flake
Browser and live serverHTTP requests, cookies, htmx swaps, pollingTwo windows disagree, a swap lands late, a session is missing

The rule of thumb that follows: when a browser test fails in a way you do not understand, first ask which border it failed on. That question narrows the search from "anything" to one of three known families, each with a known fix. The rest of this chapter takes the borders one at a time.

Example: one booking, walked across the borders

Take the main journey at Cogwell: Morgan Fell, a new customer, books Dev at Kelham Island for next Saturday at 9am.

  1. The test thread creates the workshop and Dev, and commits them. (Border one: if they were not committed, the server would not see them.)
  2. The test thread opens a fresh browser context with no cookies, like a visitor arriving for the first time. (Border three: whatever the browser carries, the server sees.)
  3. The test thread tells the browser to open the booking page, choose "09:00 with Dev", type a name, an email address and the bike, and press "Book this slot". (Border two: each command waits until its element is ready.)
  4. The browser posts the form. The live server thread validates it, saves the booking, queues the confirmation email and redirects. (Border three.)
  5. The test thread asks the browser whether "Booked. See you on Saturday." is on the screen, and keeps asking until it is or until five seconds pass. (Border two.)
  6. The test thread reads the database and the email outbox, which the server thread wrote to. (Border one again.)

Six steps, and every one of them crosses a border. Hold on to that picture. It explains why each tool in this chapter exists.

Tap or click to enlarge

The seam rule, carried over, and the scenario that changes sides

The second idea decides how many of these tests you write, and it comes straight from the Rails chapter. There, every system test has to complete one sentence: "This test fails if ___, and no faster test would notice." The blank must be a seam, a place where two technologies meet and each assumes something about the other. The rule carries over to Django unchanged. Only the list of seams is different, because the technologies are.

Django's test client already sends requests to your views, follows redirects, checks templates and reads the database, in milliseconds and with no browser at all. So in a Django application with htmx, the seams a browser can see and the test client cannot are these:

  • Server and htmx. htmx swaps a fragment, a polling timer fires, a CSRF token travels in a header that htmx adds from the <body> tag. The test client runs none of this.
  • Two people at once. Two screens, two sessions, two stale pages. The browser holds cookies and page state per window, so it is the honest way to show what one person sees after another person acts.
  • The page as assembled. Static files are served, template inheritance is complete, labels belong to their fields, and the roles a screen reader announces actually exist. The test client sees HTML as text. The browser sees a working page.

Now the interesting part. Apply the rule to the same scenario in both stacks, and one scenario changes sides.

"Someone else takes the slot first" is a browser test in the Rails chapter, and rightly so. The Rails booking form is submitted by Turbo, and Turbo shows a failed form only if the server answers with an error status such as 422. Answer with 200 and the customer sees nothing at all. That is a seam. In the Django spike, the booking form is a plain HTML form with no htmx on it. The browser submits it, the server renders the form again with the message, and the browser shows whatever comes back. There is no seam, so the scenario runs through the test client.

The seam is not gone for good, though. If Owen later submits the form with hx-post, it comes back in mirror image: htmx's own documentation says 400 level error responses are normally not swapped2. Answer a failed htmx form with 422, and the message never appears. Answer with 200, and it does. Turbo wants the error status, htmx ignores it by default. The rule tells you to move the scenario back into the browser on the day the form gets its hx-post.

Example: Cogwell's seam list, in Django

Priya and Owen wrote the sentence for the same candidates as in the Rails chapter.

BugSeam in Django?Fastest test that catches it
Two bookings for the same mechanic and slotNoModel test plus the database constraint
A slot taken while the customer types shows no messageNo, while the form is plain HTML. Yes, once it uses hx-postTest client today
The main booking journey does not fit together in a browserYes, the page as assembledBrowser, once
The price of a repair includes VAT at 20%NoUnit test
A mechanic sees another workshop's job cardsNoTest client
A move on a tablet never reaches the wall screenYes, server and htmx polling, two peopleBrowser with two windows
Two presses on the same card move it twiceYes, two people on stale pagesBrowser, plus a service test underneath
The confirmation email goes to the wrong addressNo, but it costs one line at the end of the browser journeyAsserted there, tested in depth with the test client

Eight candidates, three browser tests and one extra check, against three in the Rails list. The numbers are close. Which tests land in the browser is not, and that is the lesson: the rule is shared, the seams belong to the stack.

Why fewer browser tests is a matter of arithmetic

Every browser test has some small chance of failing for a reason that has nothing to do with your code: a slow machine, a font loading late, a timer firing a moment early. Call that chance pp. If the tests fail independently, the chance that a run of nn browser tests is entirely green is:

P(green)=(1−p)nP(\text{green}) = (1 - p)^{n}

P(green)P(\text{green}) is the probability that the whole browser suite passes on a run where the code is correct, pp is the chance that one browser test fails spuriously on one run, and nn is the number of browser tests. Foundations: probability

The formula multiplies independent chances: every test must pass, and each passes with probability 1−p1 - p. The Rails chapter held nn at 38 and varied pp. Here I hold pp and vary nn, because the number of browser tests is the part you decide.

Example: what a 0.5% flake rate does as the suite grows

Assume each browser test fails spuriously once in 200 runs, so p=0.005p = 0.005. That is a good suite, not a bad one.

  • With Cogwell's four browser tests: 0.9954≈0.9800.995^{4} \approx 0.980. One run in 50 goes red for nothing.
  • With 34 browser tests, the size the Django version reaches after two years: 0.99534≈0.8430.995^{34} \approx 0.843. About one run in six goes red for nothing.
  • With 100: 0.995100≈0.6060.995^{100} \approx 0.606. Four runs in ten.
  • With 300, the number you reach if every feature gets a browser test "to be safe": 0.995300≈0.2220.995^{300} \approx 0.222. Almost four runs in five.

Each browser test you add multiplies the chance of a false alarm, so each must earn its seat. A suite that cries wolf on most runs is worse than a smaller suite people trust, because people stop reading the failures.

With a spurious failure rate of 0.5% per test, 4 browser tests pass together 98.0% of the time, 10 tests 95.1%, 34 tests 84.3%, 100 tests 60.6% and 300 tests 22.2%. Tap or click to enlarge

Django's own tools: LiveServerTestCase and StaticLiveServerTestCase

Django ships the live server itself. The documentation describes LiveServerTestCase as doing what TransactionTestCase does, plus launching a live Django server in the background during setup and shutting it down at teardown3. The server listens on localhost on a free port the operating system picks, and the test reads its address from self.live_server_url3.

StaticLiveServerTestCase is the subclass you almost always want. It serves static files the way the development server does with DEBUG=True, without running collectstatic first3. That matters more than it sounds: Django runs every test with DEBUG=False, whatever your settings say4, so with the plain LiveServerTestCase your htmx file would not load, and every htmx feature would silently do nothing.

Django's documentation shows these classes with Selenium, the long established browser automation project, and asks for Selenium 4.8 or later3. Selenium 4.21.0, released on 16 May 2024, is current at the time of writing5. Since version 4.6, Selenium Manager finds or downloads the right browser driver for you, so the old step of installing chromedriver by hand is gone6.

Example: the workshop board in Chrome with Selenium

This is the smallest honest browser test of the board, in Django's own unittest style. JobCardFactory comes from the TDD chapter.

# repairs/tests/test_board_selenium.py
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from django.urls import reverse
from selenium.webdriver import Chrome, ChromeOptions
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait

from tests.factories import JobCardFactory


class BoardInChromeTests(StaticLiveServerTestCase):
    @classmethod
    def setUpClass(cls):
        super().setUpClass()
        options = ChromeOptions()
        options.add_argument("--headless=new")  # no window, as on a CI machine
        cls.browser = Chrome(options=options)  # Selenium Manager finds the driver

    @classmethod
    def tearDownClass(cls):
        cls.browser.quit()
        super().tearDownClass()

    def test_start_repair_moves_the_card(self):
        job = JobCardFactory(booking__problem="Puncture on the Blue Brompton")
        # Sign in by handing the browser a session cookie.
        self.client.force_login(job.booking.mechanic.user)
        self.browser.get(self.live_server_url + "/")  # a cookie needs a page on the domain first
        self.browser.add_cookie({"name": "sessionid", "value": self.client.cookies["sessionid"].value})

        self.browser.get(self.live_server_url + reverse("repairs:board", args=[job.booking.workshop.pk]))
        self.browser.find_element(By.XPATH, "//button[text()='Start repair']").click()

        # An explicit wait: check again and again until it holds, at most 5 seconds.
        WebDriverWait(self.browser, 5).until(
            EC.text_to_be_present_in_element((By.ID, "column-in_repair"), "In repair (1)")
        )

Run it with python manage.py test repairs. Read the last statement carefully, because it is the whole story of Selenium and flakiness. Selenium does what you say, at once. After click(), the htmx request is still in flight, so a plain find_element on the next line would often see the old board. WebDriverWait repeats the check until it holds. Selenium's own documentation calls this race between the browser and your instructions a major cause of flaky tests, and warns against mixing implicit and explicit waits, because the timeouts can add up in unpredictable ways7. Django's example sets an implicit wait of 10 seconds in setUpClass3. If you also use WebDriverWait, pick one style and drop the other.

The database transaction trap

Now the first border. Most of the Django tests you write use TestCase, which wraps each test in a transaction and rolls it back at the end3. That is why those tests are fast and clean. It is also why they cannot work with a live server.

A transaction that has not been committed is visible only to the database connection that opened it. The live server thread has its own connection. So rows your test created inside a TestCase transaction are invisible to the server: the browser sees an empty board, or a login page, because the session row is not there either. pytest django says it plainly: the live server and the tests run in different threads, so they cannot share a database transaction, and that is why its live_server fixture depends on transactional_db8.

LiveServerTestCase avoids the trap by being a TransactionTestCase. Your data is really committed, and Django empties the tables after each test instead of rolling back3. That fix has two costs worth knowing:

  • Data from migrations disappears. Django's documentation says data loaded in migrations is only available in TestCase tests, not in TransactionTestCase tests, and that includes the live server classes4. If Cogwell's six workshops came from a data migration, the first browser test would wipe them. You can restore them per test with serialized_rollback = True, which the documentation says slows that suite down roughly threefold4. My advice: create what each test needs with factories and never rely on migration data in a browser test.
  • Order starts to matter. An emptied table can surprise a later test that expected migration data. Django's test runner therefore runs all TestCase classes first and the others afterwards4, and pytest django reorders tests the same way, putting transactional ones last9.

There is one more twist, and it is the one that bites teams in continuous integration (CI). With SQLite's in memory test database, the live server thread and the test thread share one connection, as Django's documentation explains3, and pytest django passes in memory SQLite connections to the server thread in the same way10. With a shared connection there is no border at all, so a test that forgets about transactions passes on a laptop with SQLite and fails in CI on PostgreSQL. If production runs PostgreSQL, run the browser tests on PostgreSQL too.

This is also the biggest single difference from Rails. Since Rails 5.1, threads spawned by a test share one connection inside the test's transaction11, so a Rails system test can keep its fast rollback and the server still sees the data. The Rails chapter relies on exactly that. Django gives the server its own connection: slower, and closer to how a second request in production sees the world.

Example: the empty page that only failed in CI

At Cogwell, Owen writes the first pytest bdd scenario. The steps receive the live server only when pytest bdd hands it to them, part way through the test, and the module carries the ordinary @pytest.mark.django_db marker. On his laptop with SQLite, it passes. In CI with PostgreSQL, the booking page has no slots on it.

Here is what happened, border by border. pytest django decides how to wrap a test in a transaction before the test starts. Because the test did not ask for live_server up front, it got the plain db fixture: a transaction that is never committed. You can check this yourself with pytest django 4.8: print connection.in_atomic_block in a test marked django_db that requests live_server late, and it says True. Request the fixture up front and it says False. On SQLite the shared connection hid the problem. On PostgreSQL the server's own connection could not see Dev, so it offered no slots.

The fix is two lines in the end to end folder's conftest.py, shown in full in the setup section below: mark every browser test django_db(transaction=True), and request live_server in an autouse fixture so it is part of every test from the start. Then the trap is closed for every test anyone adds later.

Selenium or Playwright for Python

Two browser drivers matter for Django in June 2024, and both are good.

Selenium speaks the W3C WebDriver standard, works from many languages, drives every major browser, and is what Django's own documentation uses3. It is mature, widely known, and runs on Selenium Grid if you need many machines. Its cost is the one you just saw: you write the waiting yourself.

Playwright comes from Microsoft. Playwright for Python 1.44.0, released on 17 May 2024, is current, with the pytest plugin at 0.5.0 from 6 May 20241213. Four features make it the better fit for an htmx application, in my judgement:

  • Auto waiting. Before Playwright clicks, it checks that the element is visible, stable (not moving), enabled and actually receives the click, and it waits for those checks to pass14. A fill() waits until the field is visible, enabled and editable14.
  • Web first assertions. expect(locator).to_have_text(...) retries until the condition holds, with a default timeout of five seconds15. This is the explicit wait from the Selenium example, built into every assertion.
  • Tracing. Run pytest with --tracing retain-on-failure and every failing test leaves a trace: each action, the page before and after it, the network and the console, which you open with playwright show-trace16.
  • Codegen. playwright codegen opens a browser, records what you click, and writes the Python for it17. It is a good way to find locators, and a poor way to write the final test.

Playwright also prefers locators by role and label, the way a person or a screen reader finds things, over CSS classes18. That ties browser tests to the accessibility work in the front end chapter: if get_by_label("Your name") cannot find the field, a screen reader user cannot either. The Rails chapter makes the same point about Capybara's fill_in.

My view: for a new Django project with htmx, I would start with Playwright and pytest. Selenium remains a sound choice where a team already has Selenium skills, a Grid, or tests in several languages. The test that waits correctly matters more than the library.

Selenium 4.21Playwright for Python 1.44
WaitingYou write it (WebDriverWait), or set an implicit waitBuilt into every action and every expect
BrowsersChrome, Firefox, Edge, Safari through WebDriverChromium, Firefox and WebKit builds it downloads itself
Failure evidenceScreenshots you take yourselfScreenshots, video and a full trace from command line flags
Test runnerAny. Django's examples use unittestAny. The official plugin is for pytest
RecordingSelenium IDE, a browser extensionplaywright codegen

Example: the same click and check, in both

The Selenium version from above:

self.browser.find_element(By.XPATH, "//button[text()='Start repair']").click()
WebDriverWait(self.browser, 5).until(
    EC.text_to_be_present_in_element((By.ID, "column-in_repair"), "In repair (1)")
)

The Playwright version:

page.get_by_role("button", name="Start repair").click()
expect(page.locator("#column-in_repair")).to_have_text("In repair (1)")

Same behaviour. In the second, the waiting is not something you can forget.

Setting up pytest, pytest django and Playwright

Install the packages at the versions current in June 2024 and download a browser:

python -m pip install "pytest-django==4.8.0" "pytest-playwright==0.5.0" \
    "playwright==1.44.0" "pytest-bdd==7.2.0" "factory_boy==3.3.0"
python -m playwright install chromium

Then a settings module for tests. The application queues its emails through Celery, as set up in the background tasks chapter. In tests there is no worker, so Celery should run each task at once, in the request that queued it. Celery's task_always_eager setting does exactly that19, written CELERY_TASK_ALWAYS_EAGER because the Celery app reads Django settings with the CELERY prefix.

# cogwell/settings_test.py
from .settings import *  # noqa: F403

# Celery runs each task at once, inside the request that queued it.
CELERY_TASK_ALWAYS_EAGER = True

# A fast password hasher: creating users is the slowest part of test data.
PASSWORD_HASHERS = ["django.contrib.auth.hashers.MD5PasswordHasher"]

# The board's polling interval. Tests may shorten it with the settings fixture.
BOARD_POLL_SECONDS = 10

BOARD_POLL_SECONDS is one small change to the board from the front end chapter: the template now reads hx-trigger="every {{ poll_seconds }}s", and board_context() passes settings.BOARD_POLL_SECONDS in. A hard coded every 10s would force a browser test to wait ten seconds for the wall screen. A setting lets the test say "every second".

The pytest configuration grows by three lines on the TDD chapter's version:

# pyproject.toml
[tool.pytest.ini_options]
DJANGO_SETTINGS_MODULE = "cogwell.settings_test"
python_files = ["tests.py", "test_*.py"]
addopts = "--reuse-db --strict-markers"
bdd_features_base_dir = "features/"
markers = ["browser: drives a real browser through Playwright"]

One more thing your setup must handle, and neither project's documentation spells it out for this combination. Playwright's sync API runs an asyncio event loop in the test's thread. Django protects its object relational mapper (ORM) from code running where an event loop is active and raises SynchronousOnlyOperation20. So the first factory call in a Playwright test fails, although nothing in it is asynchronous. The versions above reproduce it every time. Django's documented escape hatch is the environment variable DJANGO_ALLOW_ASYNC_UNSAFE, which it says to use only when you are certain nothing runs concurrently, and never in production20. In a test process it is safe for a concrete reason: the test thread is the only code using its own database connection, and the live server thread has a separate one.

Example: the conftest.py for Cogwell's browser tests

Everything in tests/e2e/ is a browser test. This file makes that true in one place.

# tests/e2e/conftest.py
import os
from pathlib import Path

import pytest
from django.conf import settings
from django.test import Client

# Playwright's sync API runs an asyncio event loop in the test's thread.
# Django sees that loop and refuses ORM calls from this thread with
# SynchronousOnlyOperation. Nothing else runs Django code in this thread
# while a test waits, so the check is switched off for the test process alone.
# Never set this anywhere near production.
os.environ.setdefault("DJANGO_ALLOW_ASYNC_UNSAFE", "true")

HERE = Path(__file__).parent


def pytest_collection_modifyitems(items):
    # This hook sees every collected test, so pick out the ones in this folder.
    for item in items:
        if item.path.is_relative_to(HERE):
            item.add_marker(pytest.mark.browser)
            # Committed transactions: the live server's thread must see our data.
            item.add_marker(pytest.mark.django_db(transaction=True))


@pytest.fixture(autouse=True)
def server(live_server):
    # Request the live server here, for every test, not only inside a step.
    # pytest bdd asks for step fixtures late, and pytest django prepares
    # the server (ALLOWED_HOSTS, the database) only for tests that ask early.
    return live_server


@pytest.fixture(scope="session")
def browser_context_args(browser_context_args, live_server):
    # Every page the plugin opens starts at the live server.
    return {**browser_context_args, "base_url": live_server.url}

Two comments in there carry lessons that only show up when you run the code. A pytest_collection_modifyitems hook in a folder's conftest.py still receives every test in the session, so without the path check every unit test in the project would be marked as a browser test, and pytest -m "not browser" would run nothing. And the autouse server fixture is the fix for Owen's empty page from the trap section.

The second half of the file deals with JavaScript errors and with signing people in.

# tests/e2e/conftest.py (continued)
@pytest.fixture
def js_errors():
    """Collects uncaught JavaScript errors. Any error fails the test."""
    errors = []
    yield errors
    assert errors == [], f"JavaScript errors in the browser: {errors}"


@pytest.fixture
def customer_page(page, js_errors):
    """A browser page for a visitor who is not signed in."""
    page.on("pageerror", lambda error: js_errors.append(str(error)))
    return page


@pytest.fixture
def signed_in_page(new_context, live_server, js_errors):
    """Open a new, isolated browser window that is already signed in as `user`."""

    def open_for(user):
        client = Client()
        client.force_login(user)  # writes a real session row the server can read
        session_id = client.cookies[settings.SESSION_COOKIE_NAME].value

        # new_context (pytest playwright 0.5) applies browser_context_args,
        # so base_url is set, and it records traces and screenshots too.
        context = new_context()
        context.add_cookies(
            [{"name": settings.SESSION_COOKIE_NAME, "value": session_id, "url": live_server.url}]
        )
        page = context.new_page()
        page.on("pageerror", lambda error: js_errors.append(str(error)))
        return page

    return open_for

Three decisions sit in these fixtures:

  • Fail on JavaScript errors. Playwright raises the pageerror event for every uncaught exception in the page21. Without the listener, a broken script can leave a page that looks right and a test that passes, until a customer presses the one button the script was meant to wire up. The Rails chapter adds the same check for the same reason.
  • Sign in without the login form. Typing a password in every test is slow and tests the login page a hundred times. The Django test client creates a real session with force_login(), and the test gives its cookie to a new browser context. A Playwright context is an isolated browser profile with its own cookies and storage22, so two contexts are two people.
  • Create contexts through new_context. This fixture arrived in pytest playwright 0.5.0, whose release notes list artefact collection with several contexts23. Contexts you open yourself with browser.new_context() still work, but the plugin knows nothing about them, so --tracing and --screenshot record nothing for them. In the spike, the first two window board test failed and left no trace at all, for exactly that reason.

BDD in Django: behave or pytest bdd

Behaviour driven development (BDD), as Dan North introduced it in 2006, is about conversations: the people who want a feature and the people who build it agree on concrete examples of behaviour before anyone writes code24. Gherkin is the plain text format those examples are often written in: Feature, Scenario, and steps that start with Given (the situation), When (the action) and Then (the outcome). A step definition is the Python function that a step's text is matched to.

Django has two serious ways to run Gherkin.

behave is a standalone BDD runner for Python, with its own command, its own environment.py for hooks and a context object that steps share. Its latest stable release on the Python Package Index is 1.2.6, from 25 February 2018. Newer work lives in the project's development versions25. behave django connects it to Django: python manage.py behave runs the features, and steps reach the live server through context.base_url or the helper context.get_url(), which also reverses URL names26. Under the hood, its test case class subclasses StaticLiveServerTestCase27, so every border from this chapter applies. Its latest release is 1.4.0, from 15 June 2020, and lists Django versions up to 3.028. Many teams run it on newer Django, but check it on 5.0 yourself before you commit to it.

pytest bdd is a pytest plugin. Scenarios become ordinary pytest tests, steps are pytest fixtures, and you run them with the normal pytest command, with markers, selection and parallel runs29. A step can publish its return value as a fixture with target_fixture, which is how one step hands an object to the next29. Version 7.2.0, from 4 June 2024, is current30.

behave with behave djangopytest bdd
How you run itpython manage.py behave, its own runnerpytest, the same runner as every other test
Sharing state between stepsThe context objectFixtures, with target_fixture
Factories, settings, mailoutboxYour own hooks in environment.pyThe pytest django fixtures you already use
Live serverBuilt in through StaticLiveServerTestCaseThe live_server fixture
Parallel runsNot built inpytest xdist, like the rest of the suite
Gherkin keywords in other languagesYes, with --lang or a # language: line31English keywords only in 7.2: the parser knows Feature, Given, When and so on32
Latest release at the datebehave 1.2.6 (2018), behave django 1.4.0 (2020)7.2.0 (June 2024)
Best fitA team that wants BDD as its own worldA team already on pytest, as Cogwell is after the TDD chapter

My view: if your project uses pytest, use pytest bdd. One runner, one set of fixtures, one report, and the Gherkin steps reuse the factories you already trust. behave is a fair choice where the scenarios are the centre of the team's process and a separate runner is a feature, not a cost.

When Gherkin earns its keep

Gherkin is a translation layer. Every step is a sentence plus a Python function that interprets it, and translation layers cost upkeep. The reasoning is the same in both frameworks, and the Rails chapter makes it in full: Gherkin pays for itself when a named person outside the development team reads the scenarios before the code exists. Without that reader, a plain test with a good name says the same thing with one layer fewer.

The Cucumber project's own advice points the same way: write steps in a declarative style, because it "describes the behaviour of the application, rather than the implementation details"33. A declarative step says "a new customer books that slot". An imperative one says "I choose 09:00 with Dev, I fill in Your name with Morgan Fell, I press Book this slot". The first survives a redesign of the form. The second breaks the moment Owen changes a label.

Declarative steps have a second benefit that I rarely see written down. A declarative step does not say which level of the stack it runs at. "The new customer confirms the booking" can be carried out by a browser, by the Django test client, or by a direct call to a service function. So one feature file, read and agreed by Hannah, can be bound scenario by scenario to the lowest cost level that can fail for that scenario's reason. That is the seam rule, applied to Gherkin. pytest bdd makes it easy, because step definitions are fixtures, and a test module's own steps take precedence over the shared ones in conftest.py.

Example: one feature file for both stacks

This is the Rails chapter's feature file, unchanged, apart from Cucumber's @javascript tags, which mean nothing to pytest bdd.

# features/book_a_repair.feature
Feature: Book a repair online
  Customers book at any hour, Friday night included.
  They pick a free slot with a mechanic and get a clear answer straight away.

  Background:
    Given Kelham Island has a mechanic called Dev

  Scenario: A new customer books a free Saturday slot
    Given Dev is free at 09:00 on Saturday
    When a new customer books that slot for a "Green Dawes Galaxy"
    Then the customer sees the booking confirmed for 09:00 with Dev
    And Dev has exactly one booking at 09:00 on Saturday

  Scenario: Someone else takes the slot first
    Given Dev is free at 09:00 on Saturday
    And a new customer has started booking that slot
    But another customer books the same slot first
    When the new customer confirms the booking
    Then the new customer is asked to pick another time
    And nothing the new customer typed is lost

Hannah can read one file and know that both versions of the spike promise the same behaviour. The first scenario runs in a browser in both stacks. The second runs in a browser in Rails and through the test client in Django, for the reason the seam section gave.

Test data that does not rot

Before the steps, the data. The TDD chapter's factories do almost everything a browser test needs. Two rules keep browser test data honest on top of them.

Every test builds its own world. No shared fixtures file that every test leans on, no data left from the test before. With transaction=True the tables are emptied after each test anyway, so a test that relies on another test's leftovers fails as soon as the order changes.

Never hard code a date. Cogwell's booking form offers only future slots, as it should. A test that books "Saturday 22 June" passes until 22 June 2024, then fails forever, on a day when nobody touched the code. The TDD chapter already computes next Saturday. The browser tests need other hours too, and the board needs two more fields.

Example: two additions to tests/factories.py

# tests/factories.py (additions to the TDD chapter's file)

# The new customer of the booking journey, the same person as in the Rails chapter.
NEW_CUSTOMER = {"name": "Morgan Fell", "email": "morgan@example.com"}


def next_saturday_at(hour):
    today = timezone.localdate()
    days_ahead = (5 - today.weekday()) % 7 or 7  # Monday is 0, Saturday is 5
    day = today + dt.timedelta(days=days_ahead)
    return dt.datetime(day.year, day.month, day.day, hour, 0, tzinfo=SHEFFIELD)


def next_saturday_at_nine():  # kept, so BookingFactory works unchanged
    return next_saturday_at(9)


class JobCardFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = "repairs.JobCard"

    booking = factory.SubFactory(BookingFactory)
    status = "waiting"
    # The board files each card under a workshop and a mechanic: copy both from the booking.
    workshop = factory.SelfAttribute("booking.workshop")
    mechanic = factory.SelfAttribute("booking.mechanic")

Walk through next_saturday_at(9) on the day this chapter is published, Tuesday 18 June 2024. weekday() is 1, so (5 - 1) % 7 is 4, and the date is Saturday 22 June. On a Saturday itself, (5 - 5) % 7 is 0, and or 7 turns that into the following Saturday, so the slot is never in the past, even at 10am on a Saturday. SHEFFIELD is the TDD chapter's ZoneInfo("Europe/London"), so 9am means 9am at Kelham Island, summer time or not.

The worked example, part one: the booking journey in a browser

The booking page here is the public one, as in the Rails chapter: no login, each day as a group of radio buttons with one hour slots per mechanic ("09:00 with Dev"), then "Your name", "Email" and "Your bike", and one button, "Book this slot". How the free slots are worked out is not the subject. The test only cares what a customer sees.

Steps that arrange or check data are the same at every level, so they go into the project's root conftest.py, next to the TDD chapter's fixtures:

# conftest.py (at the project root, added to the TDD chapter's fixtures)
from pytest_bdd import given, parsers, then

from bookings.models import Booking
from tests.factories import BookingFactory, MechanicFactory, next_saturday_at


# Steps that arrange or check data are the same at every level, so they live here.
@given(parsers.parse("Kelham Island has a mechanic called {name}"), target_fixture="mechanic")
def mechanic_at_kelham_island(name):
    return MechanicFactory(display_name=name, workshop__name="Kelham Island")


@given(parsers.parse("{name} is free at 09:00 on Saturday"), target_fixture="slot")
def free_saturday_slot(name):
    return next_saturday_at(9)  # free means: no booking exists, so nothing to create


@given("another customer books the same slot first")
def another_customer_books_first(mechanic, slot):
    BookingFactory(mechanic=mechanic, starts_at=slot)


@then(parsers.parse("{name} has exactly one booking at 09:00 on Saturday"))
def exactly_one_booking(mechanic, slot):
    assert Booking.objects.filter(mechanic=mechanic, starts_at=slot).count() == 1

target_fixture="mechanic" deliberately reuses the name of the TDD chapter's mechanic fixture: inside a scenario, the step's Dev replaces the default mechanic for every step and fixture that asks for one.

The browser module binds the first scenario and defines the two steps that need a browser:

# tests/e2e/test_book_a_repair.py
from django.urls import reverse
from playwright.sync_api import Page, expect
from pytest_bdd import parsers, scenario, then, when

from tests.factories import NEW_CUSTOMER


# This scenario can only fail in a browser, so it runs in one.
@scenario("book_a_repair.feature", "A new customer books a free Saturday slot")
def test_a_new_customer_books_a_free_saturday_slot():
    pass


@when(parsers.parse('a new customer books that slot for a "{bike}"'))
def book_that_slot(customer_page: Page, mechanic, slot, bike):
    page = customer_page
    page.goto(reverse("bookings:new", args=[mechanic.workshop.pk]))
    day = page.get_by_role("group", name=slot.strftime("%A %-d %B"))  # "Saturday 22 June"
    day.get_by_label(f"{slot:%H:%M} with {mechanic.display_name}").check()
    page.get_by_label("Your name").fill(NEW_CUSTOMER["name"])
    page.get_by_label("Email").fill(NEW_CUSTOMER["email"])
    page.get_by_label("Your bike").fill(bike)
    page.get_by_role("button", name="Book this slot").click()


@then(parsers.parse("the customer sees the booking confirmed for 09:00 with {name}"))
def booking_confirmed(customer_page: Page, name):
    expect(customer_page.get_by_text("Booked. See you on Saturday.")).to_be_visible()
    expect(customer_page.get_by_text(f"09:00 with {name} at Kelham Island")).to_be_visible()

Follow one run, line by line, across the borders:

  1. pytest collects test_a_new_customer_books_a_free_saturday_slot. The conftest.py in tests/e2e/ marks it as a browser test with committed data, and the autouse server fixture starts the live server (once per session) before anything else.
  2. The Background runs mechanic_at_kelham_island("Dev"): one workshop, one mechanic, committed. The first Given publishes next Saturday at 9am as the slot fixture.
  3. The When step is matched by parsers.parse, which turns {bike} into "Green Dawes Galaxy". customer_page is Playwright's own page with the JavaScript error listener attached, and page.goto() takes a path because browser_context_args set the base URL.
  4. get_by_role("group", name=...) finds the day's <fieldset> by its <legend>, the way a screen reader announces it. Inside it, get_by_label("09:00 with Dev").check() picks the radio button by its label. Each action waits until its element is ready.
  5. The click posts the form to the live server thread. The view validates, saves, queues the email (which Celery runs at once, because of CELERY_TASK_ALWAYS_EAGER) and redirects to the confirmation page.
  6. The first Then step uses expect, so it waits for the redirect and the text. No sleep anywhere.
  7. The last step, from the shared conftest.py, counts the bookings in the database from the test thread. It comes after the step that waited for the screen, for the reason the Rails chapter gives: count first and you race the request. It works at all because the data is committed and DJANGO_ALLOW_ASYNC_UNSAFE is set for this process.

On a laptop in the spike, this scenario ran in well under two seconds once the browser had started (an example value, not a benchmark).

The worked example, part two: the same file through the test client

The second scenario is bound in a different module, with its own versions of the steps that touch the user interface. Same sentences, different level.

# tests/bookings/test_book_a_repair_steps.py
import pytest
from django.urls import reverse
from pytest_bdd import given, scenario, then, when

from tests.factories import NEW_CUSTOMER

pytestmark = pytest.mark.django_db


# Same feature file, same words, bound to the Django test client:
# nothing in this scenario needs JavaScript, so it needs no browser.
@scenario("book_a_repair.feature", "Someone else takes the slot first")
def test_someone_else_takes_the_slot_first():
    pass


@given("a new customer has started booking that slot", target_fixture="typed")
def started_booking(client, mechanic, slot):
    page = client.get(reverse("bookings:new", args=[mechanic.workshop.pk]))
    slot_value = f"{mechanic.pk}@{slot:%Y-%m-%dT%H:%M}"
    assert slot_value in page.content.decode()  # the slot is on offer
    return {"slot": slot_value, **NEW_CUSTOMER, "bike": "Green Dawes Galaxy"}


@when("the new customer confirms the booking", target_fixture="response")
def confirm_booking(client, mechanic, typed):
    return client.post(reverse("bookings:new", args=[mechanic.workshop.pk]), typed)


@then("the new customer is asked to pick another time")
def asked_to_pick_another_time(response):
    assert response.status_code == 200  # the form again, not a redirect
    assert "was just taken. Please pick another time." in response.content.decode()


@then("nothing the new customer typed is lost")
def nothing_typed_is_lost(response):
    assert 'value="Morgan Fell"' in response.content.decode()

Read the steps as the customer's story. "Started booking" means the page was loaded with the slot on offer, and the customer's answers are held in a dictionary, the test client's version of a half filled form. Then the shared step books the slot for someone else. The customer submits, and the response must be the form again, with the message and with Morgan's name still in it. The slot's value, the mechanic's id and the time joined by @, is a detail of this form, and it lives in this one step, where a change to the form costs one edit.

This test runs inside an ordinary rolled back transaction, with no live server and no browser, in a few hundredths of a second. It also earned its keep on its first run in the spike. The form did not show the message. The request crashed with an IntegrityError, because the view saved the booking without catching the database's refusal. The unique constraint from the ORM chapter did its job, and the chapter's advice to catch IntegrityError in the view turned out not to be optional. The scenario found that in milliseconds, with no browser involved.

Run the whole feature with pytest -k book_a_repair, only the fast half with pytest -m "not browser", and only the browser half with pytest -m browser.

The worked example, part three: the same journey without Gherkin

For comparison, here is the first scenario as a plain Playwright test, the Django counterpart of the Rails chapter's plain system test. It adds one check the feature file does not mention: the confirmation email.

# tests/e2e/test_booking_plain.py
from django.urls import reverse
from playwright.sync_api import expect

from bookings.models import Booking
from tests.factories import MechanicFactory, next_saturday_at


def test_a_new_customer_books_a_saturday_slot_with_dev(customer_page, mailoutbox):
    dev = MechanicFactory(display_name="Dev", workshop__name="Kelham Island")
    nine = next_saturday_at(9)  # never a hard coded date

    customer_page.goto(reverse("bookings:new", args=[dev.workshop.pk]))
    day = customer_page.get_by_role("group", name=nine.strftime("%A %-d %B"))
    day.get_by_label("09:00 with Dev").check()
    customer_page.get_by_label("Your name").fill("Morgan Fell")
    customer_page.get_by_label("Email").fill("morgan@example.com")
    customer_page.get_by_label("Your bike").fill("Green Dawes Galaxy")
    customer_page.get_by_role("button", name="Book this slot").click()

    expect(customer_page.get_by_text("Booked. See you on Saturday.")).to_be_visible()
    expect(customer_page.get_by_text("09:00 with Dev at Kelham Island")).to_be_visible()
    # Screen first, then the database and the outbox: never race the request.
    assert Booking.objects.filter(mechanic=dev, starts_at=nine).count() == 1
    assert [message.to for message in mailoutbox] == [["morgan@example.com"]]

The last line hides the most interesting fact in this chapter. During tests, Django replaces the email backend with an in memory outbox3, and the live server thread runs in the same Python process, so its emails land in the same list that mailoutbox returns8. The application queues the email with transaction.on_commit, as the background tasks chapter recommends. In a plain TestCase, Django's documentation notes, those callbacks never run, because the test's transaction is never committed34. In this browser test the transaction really commits, so the email is really queued, Celery really runs it, and it really arrives. This is the one test in the suite that proves the whole chain, from button to outbox, in one go.

Plain Playwright testpytest bdd with a feature file
Files for the booking journeyOne test fileA feature file, shared steps, a browser module and a test client module
Who can read itDevelopersAnyone who knows the business
Level per scenarioWhatever the test file usesChosen per scenario, from the same sentences
Waiting and assertionsPlaywrightThe same Playwright
Cost of a form changeEdit the testEdit one step, the feature file stays
Best forSeams only developers specifyRules Hannah owns and reads

Testing htmx in the browser: wait for the result, never for the request

Now the second and third borders together. htmx makes everything asynchronous: a click sends a request, the answer arrives later, htmx swaps it into the page, and a polling timer may replace the same element a moment after that. A test that checks the page right after the click is racing htmx.

The tempting fixes are all wrong:

  • time.sleep(1) is too long on a fast machine and too short on a slow CI runner. It slows every run and still flakes.
  • Waiting for htmx's own markers. htmx puts the class htmx-request on an element while its request is in flight, and marks the target with htmx-swapping and htmx-settling around the swap2. Waiting for those classes to disappear ties the test to htmx's internals, and with polling a new request may start the moment the last one ends.
  • Waiting for the network. page.expect_response() exists and has its uses, but a response arriving is not the page showing it.

The right fix is to wait for what the user would see. "The card is now under In repair" is a fact on the screen, and expect() retries until it is true. This also survives a later change from polling to server sent events, or from htmx to something else, because it tests the behaviour, not the mechanism.

Polling needs one more thing: an interval short enough for a test. The board polls every BOARD_POLL_SECONDS, and pytest django's settings fixture changes a setting for one test and restores it afterwards8. The live server thread runs in the same process and reads the same settings object, so the change reaches the server too.

Example: the live workshop board with two browser windows

Two tests, each with two people. The first is the Rails chapter's tablet and wall screen: a move on the tablet must reach the wall screen with nobody touching it. The second exists only on the Django side. Instead of the Rails chapter's drag and drop test (this board has no drag), it proves that two presses on the same card, from two stale screens, move it only once: the conditional update from the front end chapter, seen through the eyes of the person who loses the race.

# tests/e2e/test_workshop_board.py
import re

from django.urls import reverse
from playwright.sync_api import Page, expect

from tests.factories import JobCardFactory, MechanicFactory


def column(page: Page, label):
    """The board column whose heading starts with `label`, for example "In repair"."""
    heading = page.get_by_role("heading", name=re.compile(rf"^{label} \("))
    return page.locator("section").filter(has=heading)


def card(page: Page, text):
    return page.locator("#board li").filter(has_text=text)


def test_a_move_on_a_tablet_appears_on_the_wall_screen(signed_in_page, settings):
    settings.BOARD_POLL_SECONDS = 1  # the live server thread reads the same settings
    job = JobCardFactory(booking__problem="Puncture on the Blue Brompton")
    board = reverse("repairs:board", args=[job.booking.workshop.pk])

    wall_screen = signed_in_page(job.booking.mechanic.user)
    tablet = signed_in_page(job.booking.mechanic.user)
    wall_screen.goto(board)
    expect(column(wall_screen, "Waiting")).to_contain_text("Blue Brompton")
    tablet.goto(board)

    card(tablet, "Blue Brompton").get_by_role("button", name="Start repair").click()

    # The tablet sees the move in the answer to its own POST ...
    expect(column(tablet, "In repair")).to_contain_text("Blue Brompton")
    expect(card(tablet, "Blue Brompton").get_by_role("button")).to_have_text("Mark ready")
    # ... and the wall screen within one polling interval, with no reload.
    expect(column(wall_screen, "In repair")).to_contain_text("Blue Brompton")
    expect(column(wall_screen, "Waiting")).not_to_contain_text("Blue Brompton")


def test_two_presses_on_the_same_card_move_it_only_once(signed_in_page, settings):
    settings.BOARD_POLL_SECONDS = 600  # keep both boards stale on purpose
    job = JobCardFactory(booking__problem="Puncture on the Blue Brompton")
    board = reverse("repairs:board", args=[job.booking.workshop.pk])
    colleague = MechanicFactory(display_name="Sam", workshop=job.booking.workshop)

    dev = signed_in_page(job.booking.mechanic.user)
    sam = signed_in_page(colleague.user)
    dev.goto(board)
    sam.goto(board)

    card(dev, "Blue Brompton").get_by_role("button", name="Start repair").click()
    expect(column(dev, "In repair")).to_contain_text("Blue Brompton")

    # Sam still sees the old board and presses the same, now stale, button.
    card(sam, "Blue Brompton").get_by_role("button", name="Start repair").click()

    expect(sam.get_by_role("status")).to_contain_text("Someone else moved this card")
    expect(column(sam, "In repair")).to_contain_text("Blue Brompton")
    expect(column(sam, "Ready")).not_to_contain_text("Blue Brompton")
    job.refresh_from_db()
    assert job.status == "in_repair"

Read the first test as a story. The wall screen and the tablet are two contexts, so two separate windows with separate cookies, both signed in as Dev, the way a workshop's devices are. The wall screen opens the board and shows the Blue Brompton under "Waiting". Dev taps "Start repair" on the tablet. htmx posts the form with the CSRF token from the <body> tag's hx-headers, the server moves the card with its conditional update, and the answer is the fresh board fragment, which htmx swaps in. The first two expect lines on the tablet wait for that swap. The wall screen did nothing. Within one second its polling timer fetches the board and swaps it, and the last two expect lines wait for that, well inside their five second default.

If the CSRF header were missing, the POST would get a 403, htmx would not swap the error, the board would never change, and the test would fail on the tablet's first expect: a seam the test client could never have shown.

Three details in the second test carry the lessons:

  • Stale on purpose. A 600 second interval guarantees that Sam's board is still the old one when he presses. A test about a race must control the race, or it tests luck.
  • The answer, not the timer. Sam's press is answered with the current board and the warning in its role="status" region, which the front end chapter added so screen readers announce it. The test waits for that text, exactly as a person would.
  • The database at the end. The screen says the card is in repair. The last two lines check that the data agrees: one press won, the other changed nothing.

The column() helper finds a column by its heading's accessible name, with a regular expression for "In repair (" so the card count in brackets does not matter. Where the Rails chapter scopes with within("#column_in_repair"), this test scopes by what a person reads.

Screenshots, traces and video when a test fails

A browser test that fails without evidence wastes an afternoon. The pytest plugin records three kinds of evidence from command line flags35:

  • --screenshot only-on-failure saves a picture of each page at the moment of failure.
  • --video retain-on-failure records the whole test and keeps the file only if it fails.
  • --tracing retain-on-failure saves a trace for failing tests only.

Everything lands in test-results/ unless --output says otherwise35. Of the three, the trace is the one I would never switch off. It holds every action, a snapshot of the page before and after it, the network requests and the console, and you can step through it with playwright show-trace or at trace.playwright.dev without installing anything16.

Example: reading the trace of a wall screen that never updated

A week into the spike, Owen tidies the board test and loses the line settings.BOARD_POLL_SECONDS = 1. Here is the failure, and how the trace explains it:

  1. He runs pytest -m browser --tracing retain-on-failure --screenshot only-on-failure.
  2. The failing test leaves a folder under test-results/ with two traces and two screenshots, one per browser context, because both were opened through new_context.
  3. The error message says the "In repair" column contained "In repair (0) No cards" for five seconds. On its own, that reads like a broken board.
  4. playwright show-trace on the tablet's trace shows the click, the POST and the swapped board with the card under "In repair". The tablet is fine.
  5. The wall screen's trace shows the network tab: the page load, and then no request to the board URL at all within the five seconds.
  6. No request means no poll. The interval is back at its default of 10 seconds, longer than expect waits.

Two minutes from red to cause, and the cause was on the third border, between the browser and the server, not in the board. Without the trace, the screenshot alone would have shown an unchanged wall screen and left everyone suspecting htmx.

Running headless in continuous integration

Playwright runs headless by default, and --headed is the flag to see the window35. On a CI machine the browser and the system libraries it needs must be installed first, and playwright install --with-deps chromium does both on Linux. The full pipeline, with PostgreSQL and Redis as services, caching, and how to keep the suite under seven minutes, is the subject of the last chapter of this series. Here is only the part that belongs to browser tests.

Example: the browser job's steps

# Part of a GitHub Actions job, after checkout, Python setup and pip install
- name: Install the browser
  run: python -m playwright install --with-deps chromium

- name: Fast tests first
  run: pytest -m "not browser"

- name: Browser tests
  run: pytest -m browser --tracing retain-on-failure --screenshot only-on-failure

- name: Keep the evidence of failures
  if: failure()
  uses: actions/upload-artifact@v4
  with:
    name: playwright-traces
    path: test-results/

The order is deliberate. The fast tests run first, so a broken model fails in seconds, before a browser starts. The browser tests run against PostgreSQL, because of the shared connection twist from the trap section. And the traces are uploaded only when something failed, so the person reading the red build can open the trace without running anything locally.

Rails and Django end to end tooling side by side

The Cogwell spike built both versions, so here is the same job in both stacks, as of June 2024.

JobRails 7.1Django 5.0
Browser test baseActionDispatch::SystemTestCase, system tests built in since Rails 5.136StaticLiveServerTestCase, or pytest with the live_server fixture
Driving the browserCapybara with Selenium by default, or Cuprite for ChromeSelenium, or Playwright for Python with its pytest plugin
WaitingCapybara's finders and matchers retry, by default for up to 2 seconds37Playwright's actions and expect retry, by default for up to 5 seconds15
Database during the testTest and server threads share one connection inside the test transaction11The server has its own connection, so test data must be committed
GherkinCucumber with cucumber railspytest bdd, or behave with behave django
Signing inA helper that logs in through the formforce_login plus the session cookie in a browser context
Evidence on failureA screenshot taken automatically on failure36Screenshots, video and traces from pytest flags
Live updates under testTurbo Streams over Action Cable, wait for the stream to connecthtmx polling, shorten the interval with a setting
Error responses from a formTurbo needs 422 to show a failed formhtmx does not swap 4xx responses by default

The most important row is the database one. Rails shares the test thread's connection with the server thread, so a system test keeps its transactional rollback and its data is visible to the server. Django gives the server its own connection, which is why every problem in the trap section exists in Django and mostly does not in Rails. Neither is wrong. Rails trades realism for speed and simplicity: the server sees data no second connection in production could see. Django trades speed for realism: the server sees exactly what a real second connection would. You simply need to know which world you are in.

For the person paying for this

You will not read these tests, and you do not need to. Four questions tell you whether the browser tests are an asset or a cost:

  1. "How many browser tests are there, and what does each one protect that no faster test can?" A good answer names journeys and seams: booking, the live board, two people at once. A bad answer is "every page has one".
  2. "How often does the build go red when nothing is broken?" If the honest answer is "now and then, we just rerun it", the arithmetic in this chapter applies: the suite is training your team to ignore failures.
  3. "When a browser test fails, what do you look at?" You want to hear "the trace", or at least "the screenshot and the logs". Silence means hours lost per failure.
  4. "Can you show me the scenario for the feature I asked for?" If the team uses Gherkin, you should be able to read it and recognise your own words. If you cannot, the Gherkin layer is costing money and buying nothing.

These are the questions I would want answered about my own work on a Rails project, where I write tests first and use Cucumber for the scenarios a client reads. If you want to go through them for an application you are planning, the free workshop is the place, and you can see how I build web applications before you book.

My view

Browser tests are the most expensive tests you own, and the only ones that see what your customers see. Both facts are true, so the job is selection, not volume.

My view, for a server rendered Django application with htmx:

  • Write a browser test only where it can fail for a reason the test client cannot see: htmx and JavaScript, two people at once, or the page as assembled. Everything else goes one level down.
  • Use pytest, pytest django and Playwright. Commit the data with transaction=True, request the live server up front, set DJANGO_ALLOW_ASYNC_UNSAFE for the test process only, open contexts through new_context, and fail on JavaScript errors.
  • Use Gherkin when Hannah, or your Hannah, reads the scenarios. Then use pytest bdd, keep the steps declarative, and bind each scenario to the lowest cost level that can catch its bug.
  • Never sleep. Wait for what the user would see, with expect.
  • Run browser tests on the same database engine as production, and keep traces of every failure.

What is documented here: the live server classes, the transaction behaviour, the async safety check, Playwright's waiting and tracing. What is community consensus: Selenium, Playwright and Capybara all document the race between test and browser, and all recommend waiting assertions over sleeps. What is my judgement: the three borders, binding one feature file to several levels, and Playwright over Selenium for a new htmx project.

Conclusion

A Django end to end test is three actors at once: your test, a live server thread and a browser. Every hard problem sits on one of their borders. Data must be committed for the server to see it, which is why the live server classes are transactional and why SQLite can hide the problem until CI. Commands must wait for the page, which Playwright builds into every action and assertion. And htmx changes the page after the response, so tests wait for what a person sees, never for a timer.

The worked example shows all of it on Cogwell's spike. The Rails chapter's feature file runs unchanged in Django: one scenario in a browser, one through the test client, because the seam that makes it a browser test in Rails does not exist in a plain Django form. Two browser windows prove that the live board updates and that a stale press cannot move a card twice. Traces turn a red build into a two minute diagnosis. Four browser tests protect the journeys that matter, and everything else runs in milliseconds below them.

The last chapter of this series takes both suites, Rails and Django, into continuous integration and shows how to keep them fast and trustworthy as they grow.

If you want browser tests that protect the journeys your business depends on, without a suite that cries wolf, book the free workshop: we go through your key journeys together, and the first two weeks of work are on me.

Sources

  1. 1.

    htmx, Release v2.0.0, GitHub, 17 June 2024, https://github.com/bigskysoftware/htmx/releases/tag/v2.0.0

  2. 2.

    htmx, Documentation (request indicators, swapping, modifying swapping behaviour with events), version 1.9.12, https://github.com/bigskysoftware/htmx/blob/v1.9.12/www/content/docs.md

  3. 3.

    Django Software Foundation, Testing tools: LiveServerTestCase, StaticLiveServerTestCase, TransactionTestCase and Email services, Django 5.0 documentation, https://docs.djangoproject.com/en/5.0/topics/testing/tools/

  4. 4.

    Django Software Foundation, Writing and running tests: order in which tests are executed, rollback emulation, other test conditions, Django 5.0 documentation, https://docs.djangoproject.com/en/5.0/topics/testing/overview/

  5. 5.

    Selenium project, selenium 4.21.0, Python Package Index, 16 May 2024, https://pypi.org/project/selenium/4.21.0/

  6. 6.

    Selenium project, Selenium Manager, Selenium documentation, https://www.selenium.dev/documentation/selenium_manager/

  7. 7.

    Selenium project, Waiting strategies, Selenium documentation, https://www.selenium.dev/documentation/webdriver/waits/

  8. 8.

    pytest django contributors, Django helpers: live_server, transactional_db, settings, mailoutbox, pytest django documentation, https://pytest-django.readthedocs.io/en/latest/helpers.html

  9. 9.

    pytest django contributors, plugin.py, pytest_collection_modifyitems (test ordering), version 4.8.0, GitHub, https://github.com/pytest-dev/pytest-django/blob/v4.8.0/pytest_django/plugin.py

  10. 10.

    pytest django contributors, live_server_helper.py, version 4.8.0, GitHub, https://github.com/pytest-dev/pytest-django/blob/v4.8.0/pytest_django/live_server_helper.py

  11. 11.

    Rails core team, Ruby on Rails 5.1 release notes, Rails Guides, https://guides.rubyonrails.org/v7.1/5_1_release_notes.html

  12. 12.

    Microsoft, playwright 1.44.0, Python Package Index, 17 May 2024, https://pypi.org/project/playwright/1.44.0/

  13. 13.

    Microsoft, pytest playwright 0.5.0, Python Package Index, 6 May 2024, https://pypi.org/project/pytest-playwright/0.5.0/

  14. 14.

    Microsoft, Auto waiting (actionability checks), Playwright for Python documentation, https://playwright.dev/python/docs/actionability

  15. 15.

    Microsoft, Assertions, Playwright for Python documentation, https://playwright.dev/python/docs/test-assertions

  16. 16.

    Microsoft, Trace viewer, Playwright for Python documentation, https://playwright.dev/python/docs/trace-viewer-intro

  17. 17.

    Microsoft, Generating tests (codegen), Playwright for Python documentation, https://playwright.dev/python/docs/codegen-intro

  18. 18.

    Microsoft, Locators, Playwright for Python documentation, https://playwright.dev/python/docs/locators

  19. 19.

    Celery project, Configuration and defaults: task_always_eager, Celery documentation, https://docs.celeryq.dev/en/stable/userguide/configuration.html#task-always-eager

  20. 20.

    Django Software Foundation, Asynchronous support: async safety, Django 5.0 documentation, https://docs.djangoproject.com/en/5.0/topics/async/#async-safety

  21. 21.

    Microsoft, Page class, event pageerror, Playwright for Python documentation, https://playwright.dev/python/docs/api/class-page#page-event-page-error

  22. 22.

    Microsoft, Isolation (browser contexts), Playwright for Python documentation, https://playwright.dev/python/docs/browser-contexts

  23. 23.

    Microsoft, playwright pytest release v0.5.0 (support artifact collection with multiple contexts), GitHub, 6 May 2024, https://github.com/microsoft/playwright-pytest/releases/tag/v0.5.0

  24. 24.

    Dan North, Introducing BDD, Better Software magazine, March 2006, https://dannorth.net/introducing-bdd/

  25. 25.

    behave contributors, behave 1.2.6, Python Package Index, 25 February 2018, https://pypi.org/project/behave/1.2.6/

  26. 26.

    behave django contributors, Web browser automation and test isolation, behave django documentation, version 1.4.0, GitHub, https://github.com/behave/behave-django/blob/1.4.0/docs/webbrowser.rst

  27. 27.

    behave django contributors, testcase.py, version 1.4.0, GitHub, https://github.com/behave/behave-django/blob/1.4.0/behave_django/testcase.py

  28. 28.

    behave django contributors, behave django 1.4.0, Python Package Index, 15 June 2020, https://pypi.org/project/behave-django/1.4.0/

  29. 29.

    pytest bdd contributors, pytest bdd documentation, version 7.2.0, https://pytest-bdd.readthedocs.io/en/7.2.0/

  30. 30.

    pytest bdd contributors, pytest bdd 7.2.0, Python Package Index, 4 June 2024, https://pypi.org/project/pytest-bdd/7.2.0/

  31. 31.

    behave contributors, Using behave: command line options (--lang), behave documentation, version 1.2.6, GitHub, https://github.com/behave/behave/blob/v1.2.6/docs/behave.rst

  32. 32.

    pytest bdd contributors, parser.py (STEP_PREFIXES), version 7.2.0, GitHub, https://github.com/pytest-dev/pytest-bdd/blob/7.2.0/src/pytest_bdd/parser.py

  33. 33.

    Cucumber, Writing better Gherkin, Cucumber documentation, https://cucumber.io/docs/bdd/better-gherkin/

  34. 34.

    Django Software Foundation, Database transactions: performing actions after commit, use in tests, Django 5.0 documentation, https://docs.djangoproject.com/en/5.0/topics/db/transactions/#use-in-tests

  35. 35.

    Microsoft, Pytest plugin reference, Playwright for Python documentation, https://playwright.dev/python/docs/test-runners

  36. 36.

    Rails core team, Testing Rails applications: system testing and the screenshot helper, Rails Guides for Rails 7.1, https://guides.rubyonrails.org/v7.1/testing.html#system-testing

  37. 37.

    Capybara contributors, Capybara README: asynchronous JavaScript, GitHub, https://github.com/teamcapybara/capybara#asynchronous-javascript-ajax-and-friends

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