Testing and QA · Intermediate · 24 min
Write acceptance tests with Given, When, Then and pytest-bdd
By Padding · Updated 18 Nov 2026
Debian (python:3.15-slim) · Python 3.15 · pytest 9.2.0 · pytest-bdd 9.0.1 · uv 0.13
You will turn examples agreed with a product owner into Gherkin scenarios for a small room-booking module, wire them to pytest with pytest-bdd step definitions, parsers and fixtures, cover a rule table with a scenario outline, and judge when the extra layer pays for itself.
On this page
An acceptance test checks that a feature does what the people who asked for it agreed it should do. The hard part is rarely the code. It is getting a product owner, a developer and a tester to agree on concrete examples before anyone writes the feature, and then keeping those examples honest as the code changes.
Given, When, Then is a way to write those examples so all three can read them. Given sets the scene, When is the one action under test, and Then is the outcome everybody expects. Gherkin is the plain-text format for these scenarios, and pytest-bdd runs Gherkin files as ordinary pytest tests, so they sit in the same suite, use the same fixtures and fail in the same CI job as your unit tests.
You will build a small booking module for a co-working hub with two meeting rooms, write its rules as scenarios in a .feature file, and connect each line to Python with step definitions. Along the way you will pass values from the text into code with parsers, share state between steps with fixtures, test a whole table of rules with one scenario outline, and filter scenarios by tag. The last step is about when this tooling earns its place and when plain pytest is the better choice.
Step 1 · Create the project and the booking module
Make a throwaway project and add pytest and pytest-bdd as development dependencies. The ranges allow patch releases and nothing newer. pytest-bdd 9.0.1 is the first release that works with pytest 9.2, so do not go lower:
mkdir -p ~/bdd-booking-demo
cd ~/bdd-booking-demo
uv init --no-package
uv add --dev "pytest>=9.2,<9.3" "pytest-bdd>=9.0.1,<9.1"
rm main.pyCreate booking.py. A Diary holds the hub's rooms and the bookings made so far. Bookings are by the whole hour, which keeps the arithmetic out of the way. Every rule the hub cares about raises a BookingError with a message a member could read:
cat > booking.py <<'PY'
from dataclasses import dataclass
from datetime import date
OPENS = 8
CLOSES = 20
class BookingError(Exception):
pass
@dataclass(frozen=True)
class Booking:
ref: str
member: str
room: str
day: date
start: int
end: int
class Diary:
def __init__(self):
self.rooms = {}
self.bookings = []
self._next = 1
def add_room(self, name, seats):
self.rooms[name] = seats
def book(self, member, room, day, start, end, people):
if room not in self.rooms:
raise BookingError(f"there is no room called {room}")
if end <= start:
raise BookingError("a booking must end after it starts")
if start < OPENS or end > CLOSES:
raise BookingError(f"the hub is open from {OPENS:02d}:00 to {CLOSES:02d}:00")
seats = self.rooms[room]
if people > seats:
raise BookingError(f"{room} seats {seats} people")
for b in self.bookings:
if b.room == room and b.day == day and start < b.end and b.start < end:
raise BookingError(f"{room} is booked from {b.start:02d}:00 to {b.end:02d}:00")
booking = Booking(f"BK-{self._next:03d}", member, room, day, start, end)
self._next += 1
self.bookings.append(booking)
return booking
def cancel(self, ref):
self.bookings = [b for b in self.bookings if b.ref != ref]
def free_hours(self, room, day):
taken = {
hour
for b in self.bookings
if b.room == room and b.day == day
for hour in range(b.start, b.end)
}
return [hour for hour in range(OPENS, CLOSES) if hour not in taken]
PYCheck it worked
uv run python -c "import pytest_bdd, importlib.metadata as m; print(m.version('pytest-bdd'))"
uv run python - <<'PY'
from datetime import date
from booking import Diary
d = Diary()
d.add_room("Baobab", 4)
print(d.book("Amina", "Baobab", date(2026, 12, 3), 10, 12, 3).ref)
PYThe first command prints 9.0.1 or a later 9.0 release. The second prints BK-001, the reference of the first booking.
Step 2 · Turn agreed examples into a feature file
Before any Gherkin, there is a conversation. Suppose the hub manager, who owns this feature, sits down with a developer and a tester for twenty minutes. They talk through rules and, for each rule, one or two concrete examples. The tester's job is to ask "what about...?" until the edges are clear:
- A free room can be booked. Amina books Baobab on 3 December from 10:00 to 12:00 for 3 people, and gets a reference.
- Two bookings cannot overlap. Kofi already has Baobab from 10:00 to 12:00, so Amina's 11:00 to 13:00 is refused, and the message says when the room is taken.
- Back-to-back is fine. The tester asked about 12:00 to 14:00, straight after Kofi. The manager said yes: teams swap rooms on the hour.
- Cancelling frees the slot. If Kofi cancels, Baobab is free again from 10:00 to 12:00.
The back-to-back example is the valuable one. Nobody had decided it before the meeting, and a developer guessing alone could have written <= where < was wanted.
Write those examples down as a feature file. Gherkin keeps the language of the conversation: room names, people and times, not functions and return values:
mkdir -p features tests
cat > features/booking.feature <<'GHERKIN'
Feature: Book a meeting room
Members book the hub's meeting rooms by the hour, so two teams
never turn up for the same room at the same time.
Background:
Given the hub has these rooms:
| room | seats |
| Baobab | 4 |
| Iroko | 10 |
@smoke
Scenario: A free room can be booked
When Amina books Baobab on 2026-12-03 from 10:00 to 12:00 for 3 people
Then the booking is confirmed with a reference
And Baobab is taken on 2026-12-03 from 10:00 to 12:00
Scenario: An overlapping booking is refused
Given Kofi has booked Baobab on 2026-12-03 from 10:00 to 12:00
When Amina books Baobab on 2026-12-03 from 11:00 to 13:00 for 2 people
Then the booking is refused because "Baobab is booked from 10:00 to 12:00"
Scenario: A booking can start when the previous one ends
Given Kofi has booked Baobab on 2026-12-03 from 10:00 to 12:00
When Amina books Baobab on 2026-12-03 from 12:00 to 14:00 for 2 people
Then the booking is confirmed with a reference
Scenario: Cancelling a booking frees the room
Given Kofi has booked Baobab on 2026-12-03 from 10:00 to 12:00
When Kofi cancels that booking
Then Baobab is free on 2026-12-03 from 10:00 to 12:00
GHERKINA few things about the format:
- The text under
Feature:is free description. Use it for the why, in one or two sentences. Backgroundruns before every scenario in the file. Keep it to scene-setting that every scenario truly shares; here, the rooms.- The rows under
Given the hub has these rooms:are a data table. The step receives them as a list of rows. AndandButcontinue whatever keyword came before them.And Baobab is taken...is a second Then.@smokeis a tag. You will use it to select scenarios later.
Each scenario has exactly one When. If you find yourself writing "When ... And when ...", you are testing two behaviours, and a failure will not tell you which one broke.
Check it worked
Tell pytest where the features live and generate a test for every scenario in the file. Then run it before any step exists:
cat >> pyproject.toml <<'TOML'
[tool.pytest.ini_options]
testpaths = ["tests"]
pythonpath = ["."]
bdd_features_base_dir = "features"
addopts = "--strict-markers"
markers = [
"smoke: the few scenarios to run on every deploy",
"rules: one example per house rule",
]
TOML
cat > tests/test_booking.py <<'PY'
from pytest_bdd import scenarios
scenarios("booking.feature")
PY
uv run pytest -q > first-run.txt 2>&1 || echo "pytest exited with status $?"
grep -c "StepDefinitionNotFoundError" first-run.txt
tail -1 first-run.txtscenarios("booking.feature") creates one pytest test per scenario, named after the scenario title. The run fails, as it should: the status line reads pytest exited with status 1, the count is at least 4, and the summary ends with 4 failed. Each error names the first step it could not find, such as Step definition is not found: Given "the hub has these rooms:".
Step 3 · Write step definitions with parsers and fixtures
A step definition is a Python function decorated with @given, @when or @then. pytest-bdd matches each line of a scenario against the decorators' patterns and calls the function that matches.
Most steps carry values: a room, a date, a time. parsers.parse uses a format-string pattern, so {room} captures text and {people:d} captures a whole number and converts it to int. Captured names become arguments of the function. So do fixtures: any other argument name is looked up as a pytest fixture, as in a normal test.
Put the shared diary fixture in tests/conftest.py, so every feature's tests can use it:
cat > tests/conftest.py <<'PY'
import pytest
from booking import Diary
@pytest.fixture
def diary():
return Diary()
PYNow replace tests/test_booking.py with the scenarios call and the step definitions:
cat > tests/test_booking.py <<'PY'
from dataclasses import dataclass
from datetime import date
from pytest_bdd import given, parsers, scenarios, then, when
from booking import Booking, BookingError
scenarios("booking.feature")
SLOT = "{room} on {day} from {start:d}:00 to {end:d}:00"
@dataclass
class Attempt:
booking: Booking | None
error: str | None
@given("the hub has these rooms:")
def hub_rooms(diary, datatable):
header, *rows = datatable
assert header == ["room", "seats"]
for room, seats in rows:
diary.add_room(room, int(seats))
@given(parsers.parse("{member} has booked " + SLOT), target_fixture="earlier")
def existing_booking(diary, member, room, day, start, end):
return diary.book(member, room, date.fromisoformat(day), start, end, people=1)
@when(parsers.parse("{member} books " + SLOT + " for {people:d} people"), target_fixture="attempt")
def try_to_book(diary, member, room, day, start, end, people):
try:
booking = diary.book(member, room, date.fromisoformat(day), start, end, people)
except BookingError as error:
return Attempt(booking=None, error=str(error))
return Attempt(booking=booking, error=None)
@when(parsers.parse("{member} cancels that booking"))
def cancel_booking(diary, earlier, member):
assert earlier.member == member
diary.cancel(earlier.ref)
@then("the booking is confirmed with a reference")
def confirmed(attempt):
assert attempt.error is None
assert attempt.booking.ref.startswith("BK-")
@then(parsers.parse('the booking is refused because "{reason}"'))
def refused(attempt, reason):
assert attempt.booking is None
assert attempt.error == reason
@then(parsers.parse(SLOT.replace("{room}", "{room} is taken")))
def slot_taken(diary, room, day, start, end):
free = diary.free_hours(room, date.fromisoformat(day))
assert not set(range(start, end)) & set(free)
@then(parsers.parse(SLOT.replace("{room}", "{room} is free")))
def slot_free(diary, room, day, start, end):
free = diary.free_hours(room, date.fromisoformat(day))
assert set(range(start, end)) <= set(free)
PY
uv run pytest -vThree patterns are doing the work here:
target_fixturepasses results forward. The When step returns anAttempt, andtarget_fixture="attempt"makes that value a fixture for the rest of the scenario. The Then steps ask forattemptby name. The Given for Kofi's booking does the same withearlier, which the cancel step needs to know which booking to cancel.- The When step never lets an expected error escape. It records success or failure in
Attempt, and the Then decides whether that was right. If the When raised, a "refused" scenario could never reach its Then. datatableis a reserved argument. A step followed by a table receives it as a list of rows of strings, header row first. The assertion on the header catches a renamed column early, which is kinder than a confusing failure three steps later.
The SLOT string keeps the phrase "Baobab on 2026-12-03 from 10:00 to 12:00" parsed the same way in every step. Times are whole hours, as the module requires.
Check it worked
The verbose run lists four tests, one per scenario, and ends with 4 passed. The names come from the scenario titles, for example tests/test_booking.py::test_an_overlapping_booking_is_refused PASSED.
Now prove the scenarios guard the agreed rule. In booking.py, change start < b.end and b.start < end to start <= b.end and b.start <= end, the mistake the back-to-back example was there to catch, and run uv run pytest -q again. test_a_booking_can_start_when_the_previous_one_ends fails with an assertion on attempt.error. Change the line back and the suite passes again.
Step 4 · Cover a table of rules with a scenario outline
The remaining house rules are all the same shape: someone tries a booking and gets a particular refusal. Writing each as a separate scenario repeats the same three lines. A scenario outline writes the shape once, with <placeholders>, and an Examples table supplies one row per case.
Create a second feature file for the rules:
cat > features/house_rules.feature <<'GHERKIN'
Feature: House rules for room bookings
The hub refuses bookings it cannot honour, and says why,
so a member can fix the request without calling the front desk.
Background:
Given the hub has these rooms:
| room | seats |
| Baobab | 4 |
| Iroko | 10 |
@rules
Scenario Outline: A booking that breaks a house rule is refused
When Amina books <room> on 2026-12-03 from <start> to <end> for <people> people
Then the booking is refused because "<reason>"
Examples:
| room | start | end | people | reason |
| Baobab | 10:00 | 12:00 | 5 | Baobab seats 4 people |
| Iroko | 07:00 | 09:00 | 6 | the hub is open from 08:00 to 20:00 |
| Iroko | 19:00 | 21:00 | 6 | the hub is open from 08:00 to 20:00 |
| Iroko | 15:00 | 15:00 | 6 | a booking must end after it starts |
| Mango | 10:00 | 11:00 | 2 | there is no room called Mango |
GHERKIN
cat > tests/test_house_rules.py <<'PY'
from pytest_bdd import scenarios
scenarios("house_rules.feature")
PY
uv run pytest --collect-only -q tests/test_house_rules.pypytest-bdd fills each row into the step text before matching, so When Amina books <room> on ... becomes When Amina books Baobab on 2026-12-03 from 10:00 to 12:00 for 5 people. That matches the same parsers.parse pattern as before, so the outline needs no new step definitions.
Collecting works, but run the new file and every row fails:
uv run pytest -q tests/test_house_rules.py > rules-run.txt 2>&1 || echo "pytest exited with status $?"
tail -1 rules-run.txtThe summary reads 5 failed, with StepDefinitionNotFoundError for the first step. pytest-bdd step definitions are fixtures under the hood, so a test module only sees steps defined in itself, in a conftest.py above it, or in a plugin. The steps live in tests/test_booking.py, where the house rules cannot reach them.
Move them to tests/steps.py, load that from tests/conftest.py with pytest_plugins, and cut tests/test_booking.py back to its scenarios call:
cat > tests/steps.py <<'PY'
from dataclasses import dataclass
from datetime import date
from pytest_bdd import given, parsers, then, when
from booking import Booking, BookingError
SLOT = "{room} on {day} from {start:d}:00 to {end:d}:00"
@dataclass
class Attempt:
booking: Booking | None
error: str | None
@given("the hub has these rooms:")
def hub_rooms(diary, datatable):
header, *rows = datatable
assert header == ["room", "seats"]
for room, seats in rows:
diary.add_room(room, int(seats))
@given(parsers.parse("{member} has booked " + SLOT), target_fixture="earlier")
def existing_booking(diary, member, room, day, start, end):
return diary.book(member, room, date.fromisoformat(day), start, end, people=1)
@when(parsers.parse("{member} books " + SLOT + " for {people:d} people"), target_fixture="attempt")
def try_to_book(diary, member, room, day, start, end, people):
try:
booking = diary.book(member, room, date.fromisoformat(day), start, end, people)
except BookingError as error:
return Attempt(booking=None, error=str(error))
return Attempt(booking=booking, error=None)
@when(parsers.parse("{member} cancels that booking"))
def cancel_booking(diary, earlier, member):
assert earlier.member == member
diary.cancel(earlier.ref)
@then("the booking is confirmed with a reference")
def confirmed(attempt):
assert attempt.error is None
assert attempt.booking.ref.startswith("BK-")
@then(parsers.parse('the booking is refused because "{reason}"'))
def refused(attempt, reason):
assert attempt.booking is None
assert attempt.error == reason
@then(parsers.parse(SLOT.replace("{room}", "{room} is taken")))
def slot_taken(diary, room, day, start, end):
free = diary.free_hours(room, date.fromisoformat(day))
assert not set(range(start, end)) & set(free)
@then(parsers.parse(SLOT.replace("{room}", "{room} is free")))
def slot_free(diary, room, day, start, end):
free = diary.free_hours(room, date.fromisoformat(day))
assert set(range(start, end)) <= set(free)
PY
cat > tests/conftest.py <<'PY'
import pytest
from booking import Diary
pytest_plugins = ["tests.steps"]
@pytest.fixture
def diary():
return Diary()
PY
cat > tests/test_booking.py <<'PY'
from pytest_bdd import scenarios
scenarios("booking.feature")
PY
touch tests/__init__.py
rm rules-run.txt
uv run pytest -v tests/test_house_rules.py
uv run pytest -qThe empty tests/__init__.py makes tests.steps importable by name. The step code is the same as before, only moved: the feature files are now the only place that says which scenarios exist, and tests/steps.py is the only place that says what each phrase means.
Check it worked
The collect-only run at the start of this step listed five tests for the outline, one per row of Examples, each with an id such as [Baobab-10:00-12:00-5-Baobab seats 4 people]. After the move, the verbose run shows those five as PASSED, and the full suite ends with 9 passed: four scenarios plus five outline rows.
Step 5 · Keep steps declarative, not UI scripts
The most common way BDD suites go wrong is that scenarios turn into click-by-click scripts. They are written by someone looking at the screen, and they read like this:
Scenario: Book a room
Given I open "/rooms"
And I click "Baobab"
And I type "2026-12-03" into the "date" field
And I select "10:00" from the "start" dropdown
And I select "12:00" from the "end" dropdown
And I type "3" into the "people" field
And I click the "Book" button
Then I see "Booking confirmed" in the ".alert" elementEvery line is true, and almost none of it is the rule. A product owner cannot review it without the screen in front of them. It breaks when a dropdown becomes a time picker, though the booking rules have not changed. And it cannot run against anything but the browser, so it is slow.
The scenarios you wrote describe what the member does and what the hub guarantees, in the hub's words. How "Amina books Baobab..." happens is the step definition's business. Today it calls Diary.book directly. Tomorrow the same step could call an HTTP API or drive a browser through Playwright, and the feature file would not change. Rules of thumb for each line:
- Name things from the domain: rooms, members, bookings. Not pages, fields or buttons.
- One When per scenario, and make it a business action, not a gesture.
- Put the exact messages in Then only when the wording was agreed. Here it was: the manager wanted members to read why.
- Leave out values that do not matter. The Given for Kofi's booking does not say how many people, because no rule depends on it; the step fills in
people=1.
Gherkin also comes in many spoken languages. Starting a file with a # language: line, such as # language: fr for French or # language: am for Amharic, switches the keywords, and pytest-bdd supports it. The list of languages comes from the Cucumber project and does not yet cover every language your users speak, so check it before you promise one. If your product owner thinks in French or Amharic, scenarios in their language can make the review real, as long as the team that maintains the steps reads it too.
Check it worked
Search your feature files for words that belong to a screen, not to the business:
if grep -niE "click|button|field|dropdown|page|type \"|select \"" features/*.feature; then echo "UI words found"; false; else echo "no UI words in feature files"; fiIt prints no UI words in feature files. Read one scenario aloud to someone who has never seen the code. If they can tell you what the hub promises without asking what a word means, the step is at the right level.
Step 6 · Run scenarios by tag and share the results
pytest-bdd turns Gherkin tags into pytest markers, so -m selects scenarios by tag. A tag on an outline applies to every row. Because --strict-markers is on, every tag used in a feature file must be registered in pyproject.toml, which you did for smoke and rules. A tag mistyped in a feature file, such as @smok, stops the run with an error. A mistyped -m expression on the command line is not checked: it runs and deselects everything, so watch the deselected count:
uv run pytest -q -m smoke
uv run pytest -q -m rules
uv run pytest -q -m "not rules"For a product owner who wants to see what was checked, two options print the results in their own language. --gherkin-terminal-reporter shows each scenario as Gherkin with a pass or fail per scenario, and --cucumberjson writes the standard Cucumber JSON report that many CI dashboards and report viewers can read:
uv run pytest --gherkin-terminal-reporter -v -m smoke
uv run pytest -q --cucumberjson=acceptance.json
uv run python -c "import json; f = json.load(open('acceptance.json')); print(sorted(e['name'] for feature in f for e in feature['elements'])[:2])"Check it worked
The three tag runs report 1 passed, 8 deselected, 5 passed, 4 deselected and 4 passed, 5 deselected. The Gherkin reporter prints Feature: Book a meeting room and Scenario: A free room can be booked PASSED. Add a second -v (-vv) to list each step under its scenario as well. The last command prints the first two scenario names from the JSON report in alphabetical order: ['A booking can start when the previous one ends', 'A booking that breaks a house rule is refused'].
When a new scenario arrives with a step you have not written, --generate-missing prints a skeleton for every step that has no definition, which saves typing the decorators by hand:
uv run pytest --generate-missing --feature featuresIt exits without running tests. Every step here is defined, yet it may list the outline step, Amina books <room> on 2026-12-03 from <start> to <end> for <people> people, because the generator can read the step text before the Examples values are filled in. If it does, treat that as a false alarm, since the earlier run proved the outline passes. Add a scenario with a genuinely new step to features/booking.feature and run it again to see the skeleton it suggests for that step: a @given, @when or @then decorator with the step text and a function body that raises NotImplementedError.
Step 7 · Decide when BDD tooling helps and when it adds a layer
You now have two ways to write the same check: a Gherkin scenario plus a step, or a plain pytest test. Both run in the same suite. The question is which one a given rule deserves, and the answer depends on who reads it.
Gherkin pays for itself when:
- Someone outside the code reviews the examples. A product owner, a compliance lead or a client signs off on the feature file, and changes to rules arrive as changes to scenarios.
- The same phrases come back across many scenarios. Here, nine tests are built from eight step definitions. That reuse is what keeps the step layer small.
- You need a record of agreed behaviour that outlives the people in the room, such as the back-to-back decision.
It adds a layer and little else when:
- Only developers will ever read the scenarios. A well-named pytest test with
@pytest.mark.parametrizeis shorter and easier to debug, because there is no text to match. - Each scenario needs its own steps. If you write one step definition per line of every scenario, you have two copies of the test and no shared language.
- The rule is technical: a cache header, a retry count, a parser edge case. Those belong in unit tests.
A practical split many teams settle on: a small set of Gherkin scenarios, one or two per business rule, owned with the product owner, and everything else in plain pytest beneath them. If the feature files stop being read by anyone outside engineering for a few months, that is the signal to fold them back into ordinary tests.
Check it worked
Count the reuse in your own suite:
grep -cE "^@(given|when|then)" tests/steps.py
uv run pytest --collect-only -q | grep -c "::test_"The first number is 8, the step definitions. The second is 9, the tests they drive. In your own project, run the same two counts. If the first is close to the number of lines across all your scenarios, steps are not being reused, and plain pytest may serve you better. Then answer one question in writing for your team: who outside engineering will read these feature files, and when? If there is no name in the answer, start with plain pytest.
Remove the demo project when you are done:
cd ~
rm -rf ~/bdd-booking-demoNext steps
- Decide which features deserve acceptance scenarios first: write a risk-based test plan for a release.
Related tutorials
- Write bug reports that get fixedYou will turn three weak bug reports into ones a developer can act on in five minutes, and add a bug report form to a GitHub repository so every new report asks for the same facts.
- Write a one-page test strategy for a small productYou will have a one-page test strategy for a small SaaS product that records the standing testing decisions, from quality goals and automation owners to release blockers, bug triage and what you deliberately leave untested.
- Write a risk-based test plan for a releaseYou will have a test plan for one release that sets scope, scores each risk by likelihood and impact, matches testing effort to the score, and states the entry and exit criteria, environments, owners and reporting the team will use to decide whether to ship.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials