BDD with pytest-bdd and Playwright Python (Gherkin Step by Step)
Behaviour-Driven Development (BDD) describes features in plain-language scenarios that product owners, testers and developers can all read: Given a shopper is on the login page, When they log in, Then they see a greeting. pytest-bdd turns those Gherkin scenarios into ordinary pytest tests, so they run with your Playwright fixtures, markers and reports. In this lesson you will write feature files for the SQA Shop, implement step definitions with Playwright, pass values with parsers, use Scenario Outlines and data tables, share state between steps with target_fixture, run scenarios by tag, and let pytest-bdd generate missing step code.
📖 What You’ll Learn: what BDD and Gherkin are, installing pytest-bdd, a feature file with Feature, Background and Scenario, step definitions with given, when and then, binding scenarios with scenarios(), parsers.parse for values in steps, target_fixture to pass objects between steps, Scenario Outline with Examples, data tables, tags as pytest markers, –generate-missing, the gherkin terminal reporter, and good practices for readable scenarios.
🗣️ What Are BDD and Gherkin?
BDD is a way of working: before building a feature, the team agrees on examples of how it should behave. The examples are written in Gherkin, a structured plain-English format:
Feature: Coupons in the cart
Scenario: A member applies SAVE10
Given my cart contains Wireless Earbuds
When I apply the coupon "SAVE10"
Then the coupon discount is "−₹500"
| Keyword | Meaning |
|---|---|
Feature |
The capability being described |
Background |
Steps run before every scenario in the file |
Scenario |
One concrete example |
Given / When / Then |
Context / action / expected outcome |
And, But |
Continue the previous step type |
Scenario Outline + Examples |
One scenario run for every row of a table |
The scenarios become living documentation: they are executed on every run, so they cannot silently go out of date.
📦 Set Up pytest-bdd
⌨️ Terminal
pip install pytest-bdd
This lesson uses pytest-bdd 9.0. Configure where feature files live and register the tags you will use as markers:
📄 pytest.ini
[pytest]
addopts = --base-url https://sqatools.in --strict-markers
bdd_features_base_dir = features/
markers =
smoke: quick checks
coupons: coupon scenarios
📝 Step 1: A Feature File
📄 features/login.feature
@smoke
Feature: Log in to SQA Shop
As a shopper
I want to log in
So that my saved details are used at checkout
Background:
Given I am on the login page
Scenario: Successful login
When I log in as "testuser" with password "Test@123"
Then I see the greeting "Hi, Test"
Scenario Outline: Login is refused
When I log in as "<username>" with password "<password>"
Then I see the login error "<message>"
Examples:
| username | password | message |
| testuser | wrong | Invalid username or password. |
| lockeduser | Test@123 | This account is locked. Please contact support. |
| ghost | Test@123 | Invalid username or password. |
The scenarios use the business language of the shop, not locators or clicks.
🔗 Step 2: Step Definitions
Step definitions are Python functions decorated with @given, @when and @then. parsers.parse extracts the quoted values from the step text and passes them as arguments. Shared steps go in conftest.py so every feature can use them:
📄 tests/conftest.py
from playwright.sync_api import Page, expect
from pytest_bdd import given, parsers, then, when
SHOP = "/dummy-ecommerce-website/"
@given("I am on the login page")
def on_login_page(page: Page):
page.goto(SHOP + "#/login")
@when(parsers.parse('I log in as "{username}" with password "{password}"'))
def log_in(page: Page, username: str, password: str):
page.get_by_test_id("login-username").fill(username)
page.get_by_test_id("login-password").fill(password)
page.get_by_test_id("login-button").click()
@then(parsers.parse('I see the greeting "{greeting}"'))
def see_greeting(page: Page, greeting: str):
expect(page.get_by_test_id("account-button")).to_contain_text(greeting)
@then(parsers.parse('I see the login error "{message}"'))
def see_login_error(page: Page, message: str):
expect(page.get_by_test_id("login-error")).to_have_text(message)
Then bind the feature file to a test module with scenarios(), which creates one pytest test per scenario:
📄 tests/test_login.py
from pytest_bdd import scenarios
scenarios("login.feature") # path is relative to bdd_features_base_dir
⌨️ Terminal
pytest tests/test_login.py -v
🖥️ Output
============================= test session starts =============================
platform win32 -- Python 3.15.1, pytest-9.2.0, pluggy-1.7.0 -- C:\Users\you\playwright-python\.venv\Scripts\python.exe
cachedir: .pytest_cache
baseurl: https://sqatools.in
rootdir: C:\Users\you\playwright-python
configfile: pytest.ini
plugins: allure-pytest-2.16.2, base-url-2.1.0, bdd-9.0.1, html-4.2.0, metadata-3.1.1, playwright-0.10.0, rerunfailures-16.7, xdist-3.8.0
collecting ... collected 4 items
tests/test_login.py::test_successful_login PASSED [ 25%]
tests/test_login.py::test_login_is_refused[testuser-wrong-Invalid username or password.] PASSED [ 50%]
tests/test_login.py::test_login_is_refused[lockeduser-Test@123-This account is locked. Please contact support.] PASSED [ 75%]
tests/test_login.py::test_login_is_refused[ghost-Test@123-Invalid username or password.] PASSED [100%]
============================== 4 passed in 6.44s ==============================
Every scenario (and every Examples row) is a normal pytest test with a readable name. Steps receive Playwright’s page fixture like any test, so everything from earlier modules (storage state, tracing, browsers) works unchanged.
🧺 Step 3: Data Tables and target_fixture
A data table passes a small table to one step. A step can also create an object for later steps with target_fixture: its return value becomes a fixture with that name.
📄 features/coupons.feature
@coupons
Feature: Coupons in the cart
Scenario: SAVE10 is capped at ₹500
Given my cart contains:
| product | qty |
| EL-013 | 1 |
When I apply the coupon "SAVE10"
Then the coupon discount is "−₹500"
Scenario: FLAT200 needs a bigger cart
Given my cart contains:
| product | qty |
| DG-010 | 1 |
When I apply the coupon "FLAT200"
Then the coupon message is "Add ₹1,000 more to use FLAT200."
📄 tests/test_coupons.py
import json
from playwright.sync_api import BrowserContext, Page, expect
from pytest_bdd import given, parsers, scenarios, then, when
scenarios("coupons.feature")
SHOP = "/dummy-ecommerce-website/"
@given("my cart contains:", target_fixture="cart_page")
def cart_contains(context: BrowserContext, page: Page, datatable):
header, *rows = datatable # first row is the header
lines = [{"id": r[header.index("product")], "size": "", "color": "", "qty": int(r[header.index("qty")])} for r in rows]
context.add_init_script(f"if (!sessionStorage.getItem('seeded')) {{ localStorage.setItem('spCart', {json.dumps(json.dumps(lines))}); sessionStorage.setItem('seeded', '1'); }}")
page.goto(SHOP + "#/cart")
return page
@when(parsers.parse('I apply the coupon "{code}"'))
def apply_coupon(cart_page: Page, code: str):
cart_page.get_by_test_id("coupon-input").fill(code)
cart_page.get_by_test_id("apply-coupon").click()
@then(parsers.parse('the coupon discount is "{amount}"'))
def coupon_discount(cart_page: Page, amount: str):
expect(cart_page.get_by_test_id("coupon-discount")).to_have_text(amount)
@then(parsers.parse('the coupon message is "{message}"'))
def coupon_message(cart_page: Page, message: str):
expect(cart_page.get_by_test_id("coupon-message")).to_have_text(message)
⌨️ Terminal
pytest tests/test_coupons.py -v
🖥️ Output
============================= test session starts =============================
platform win32 -- Python 3.15.1, pytest-9.2.0, pluggy-1.7.0 -- C:\Users\you\playwright-python\.venv\Scripts\python.exe
cachedir: .pytest_cache
baseurl: https://sqatools.in
rootdir: C:\Users\you\playwright-python
configfile: pytest.ini
plugins: allure-pytest-2.16.2, base-url-2.1.0, bdd-9.0.1, html-4.2.0, metadata-3.1.1, playwright-0.10.0, rerunfailures-16.7, xdist-3.8.0
collecting ... collected 2 items
tests/test_coupons.py::test_save10_is_capped_at_500 PASSED [ 50%]
tests/test_coupons.py::test_flat200_needs_a_bigger_cart PASSED [100%]
============================== 2 passed in 3.56s ==============================
datatableis a built-in pytest-bdd fixture: a list of rows, each a list of cell strings.target_fixture="cart_page"makes the step’s return value available to later steps ascart_page. That is how steps share state without global variables.- Steps defined in a test module are only visible to scenarios bound in that module; steps in
conftest.pyare visible everywhere.
🏷️ Tags Become Markers
Gherkin tags (@smoke, @coupons) become pytest markers, so the usual -m selection works:
⌨️ Terminal
pytest -m coupons -q
🖥️ Output
.. [100%]
2 passed, 4 deselected in 3.61s
⌨️ Terminal
pytest -m "smoke and not coupons" -q
🖥️ Output
.... [100%]
4 passed, 2 deselected in 6.47s
Because --strict-markers is on, a tag that is not registered in pytest.ini is reported as an error, which catches typos in feature files.
🤖 Generate Missing Step Code
When a product owner adds a new scenario, pytest-bdd can write the skeleton code for you, in two passes:
📄 features/search.feature
Feature: Search
Scenario: Search finds earbuds
Given I am on the home page
When I search for "earbuds"
Then I see at least 1 product
Pass 1: the scenario is not bound to any test yet, so pytest-bdd prints a test module that binds it:
⌨️ Terminal
pytest --generate-missing --feature features/search.feature
🖥️ Output
============================= test session starts =============================
platform win32 -- Python 3.15.1, pytest-9.2.0, pluggy-1.7.0
baseurl: https://sqatools.in
rootdir: C:\Users\you\playwright-python
configfile: pytest.ini
plugins: allure-pytest-2.16.2, base-url-2.1.0, bdd-9.0.1, html-4.2.0, metadata-3.1.1, playwright-0.10.0, rerunfailures-16.7, xdist-3.8.0
collected 6 items
Scenario "Search finds earbuds" is not bound to any test in the feature "Search" in the file C:\Users\you\playwright-python\features\search.feature:3
-------------------------------------------------------------------------------
Please place the code above to the test file(s):
"""Search feature tests."""
from pytest_bdd import (
given,
scenario,
then,
when,
)
@scenario('features\search.feature', 'Search finds earbuds')
def test_search_finds_earbuds():
"""Search finds earbuds."""
============================ no tests ran in 0.02s ============================
Pass 2: bind the feature (the shorter scenarios() form does the same as the printed @scenario), then ask again. Now it prints a stub for every step that has no definition:
📄 tests/test_search.py
from pytest_bdd import scenarios
scenarios("search.feature")
⌨️ Terminal
pytest --generate-missing --feature features/search.feature
🖥️ Output
============================= test session starts =============================
platform win32 -- Python 3.15.1, pytest-9.2.0, pluggy-1.7.0
baseurl: https://sqatools.in
rootdir: C:\Users\you\playwright-python
configfile: pytest.ini
plugins: allure-pytest-2.16.2, base-url-2.1.0, bdd-9.0.1, html-4.2.0, metadata-3.1.1, playwright-0.10.0, rerunfailures-16.7, xdist-3.8.0
collected 7 items
Step Given "I am on the home page" is not defined in the scenario "Search finds earbuds" in the feature "Search" in the file C:\Users\you\playwright-python\features\search.feature:4
Step When "I search for "earbuds"" is not defined in the scenario "Search finds earbuds" in the feature "Search" in the file C:\Users\you\playwright-python\features\search.feature:5
Step Then "I see at least 1 product" is not defined in the scenario "Search finds earbuds" in the feature "Search" in the file C:\Users\you\playwright-python\features\search.feature:6
-------------------------------------------------------------------------------
Please place the code above to the test file(s):
@given('I am on the home page')
def _():
"""I am on the home page."""
raise NotImplementedError
@when('I search for "earbuds"')
def _():
"""I search for "earbuds"."""
raise NotImplementedError
@then('I see at least 1 product')
def _():
"""I see at least 1 product."""
raise NotImplementedError
============================ no tests ran in 0.02s ============================
Copy the stubs into the module, give each function a real name, and replace literal values with parsers ('I search for "{term}"'), so one step serves many scenarios. Steps that already exist, for example in conftest.py, are not generated again.
📣 Gherkin-Style Output
For demos and CI logs that business readers look at, print scenarios step by step. Here is the finished step module:
📄 tests/test_search.py
from playwright.sync_api import Page, expect
from pytest_bdd import given, parsers, scenarios, then, when
scenarios("search.feature")
@given("I am on the home page")
def home(page: Page):
page.goto("/dummy-ecommerce-website/")
@when(parsers.parse('I search for "{term}"'))
def search(page: Page, term: str):
page.get_by_test_id("search-input").fill(term)
page.get_by_test_id("search-button").click()
@then(parsers.parse("I see at least {count:d} product"))
def at_least(page: Page, count: int):
expect(page.get_by_test_id("product-card").first).to_be_visible()
assert page.get_by_test_id("product-card").count() >= count
⌨️ Terminal
pytest tests/test_search.py --gherkin-terminal-reporter -v
🖥️ Output
============================= test session starts =============================
platform win32 -- Python 3.15.1, pytest-9.2.0, pluggy-1.7.0 -- C:\Users\you\playwright-python\.venv\Scripts\python.exe
cachedir: .pytest_cache
baseurl: https://sqatools.in
rootdir: C:\Users\you\playwright-python
configfile: pytest.ini
plugins: allure-pytest-2.16.2, base-url-2.1.0, bdd-9.0.1, html-4.2.0, metadata-3.1.1, playwright-0.10.0, rerunfailures-16.7, xdist-3.8.0
collecting ... collected 1 item
tests/test_search.py::test_search_finds_earbuds
Feature: Search
Scenario: Search finds earbuds PASSED
============================== 1 passed in 1.96s ==============================
{count:d} in the parser converts the value to an int. Other format types include {price:f} for floats and {name:w} for a single word.
✅ Good Practices for Readable Scenarios
- Describe behaviour, not clicks. “When I apply the coupon SAVE10”, not “When I click the apply button”.
- One behaviour per scenario, with one
When(a scenario with fiveWhensteps tests five things). - Declarative Given steps that set up state quickly (seeded cart, saved login), not long click-paths.
- Reuse steps through
conftest.py, and keep step texts consistent so they can be shared. - Keep locators out of feature files and out of step texts; use page objects inside step definitions as the suite grows.
- Use BDD for collaboration. If nobody outside the test team reads the feature files, plain pytest tests are simpler.
💡 Tip: The Playwright TypeScript course builds the same idea with the playwright-bdd package for TypeScript, if your team works in both languages.
🏋️ Practice Exercises
Try each exercise on your own first, then open the answer to compare. The answers use the same practice sites and project layout as the lesson.
Exercise 1: Write a Scenario Outline for the SQA Shop search with three terms (earbuds, jeans, course) and a minimum result count for each, plus the step definition for the count step.
Show answer
Scenario Outline: Search returns results
Given I am on the home page
When I search for "<term>"
Then I see at least <count> product
Examples:
| term | count |
| earbuds | 1 |
| jeans | 3 |
| course | 3 |The existing @then(parsers.parse("I see at least {count:d} product")) step already handles it; <count> is substituted before parsing, and :d turns it into an int.
Exercise 2: Two feature files both need “Given I am logged in”. Where do you put the step definition, and how should it log in quickly?
Show answer
Put it in tests/conftest.py so every scenario can use it. Make it fast by loading saved login state or seeding storage instead of typing into the form, for example with a storage-state file (Lesson 51) or context.add_init_script that sets spUser in localStorage.
Exercise 3: A step “When I add the product to the cart” needs to know which product the earlier Given step opened. How do you share it without a global variable?
Show answer
Return the product from the Given step with target_fixture, then request that fixture in the When step:
@given(parsers.parse('I open the product "{product_id}"'), target_fixture="product_id")
def open_product(page, product_id):
page.goto(f"/dummy-ecommerce-website/#/p/{product_id}")
return product_id
@when("I add the product to the cart")
def add(page, product_id):
page.get_by_test_id("pdp-add-to-cart").click()Exercise 4: Your feature file has the tag @regresion (typo) and the run fails with “not found in markers”. Why is that good, and what is the fix?
Show answer
--strict-markers turned the typo into an error instead of silently ignoring the tag (which would make -m regression skip those scenarios). Fix the tag to @regression and make sure regression is registered under markers in pytest.ini.
🧠 MCQ Quiz: BDD with pytest-bdd and Playwright
10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.
- What does pytest-bdd do?Answer: Runs Gherkin feature files as pytest tests using step definition functions. Each scenario becomes a pytest test whose steps call your decorated functions.
- Which keyword describes context that every scenario in a feature needs?Answer: Background. Background steps run before each scenario in the file.
- What does
scenarios("login.feature")do?Answer: Creates one pytest test per scenario in the file, bound to the module.scenarios()generates test functions for every scenario, relative tobdd_features_base_dir. - How do you extract
"SAVE10"from the step textI apply the coupon "SAVE10"?Answer:@when(parsers.parse('I apply the coupon "{code}"'))with acodeargument. Parsers turn placeholders into function arguments. - What does
target_fixture="cart_page"on a Given step do?Answer: Makes the step’s return value available as a fixture namedcart_pageto later steps. This is pytest-bdd’s way of passing state between steps. - How does a Scenario Outline run?Answer: Once per row of its Examples table, with
<placeholders>replaced. Each Examples row becomes its own test. - What does the
datatablefixture contain?Answer: A list of rows, each a list of cell strings, including the header row. pytest-bdd passes data tables as nested lists of strings. - How are Gherkin tags such as
@smokeused in pytest?Answer: They become markers, selectable with-m smoke. pytest-bdd converts tags to pytest markers. - Where should step definitions shared by several features live?Answer: In
conftest.py. Fixtures and steps in conftest.py are visible to all tests below it. - Which step text is better BDD style?Answer: When I apply the coupon “SAVE10”. Scenarios should describe user behaviour, not UI mechanics.
Want a longer, timed test? Take the Module 10 mock interview (20 MCQs in 20 minutes).
❓ Frequently Asked Questions
🤔 pytest-bdd or behave?
behave is a standalone BDD runner with its own fixtures and hooks. pytest-bdd runs inside pytest, so you keep pytest-playwright fixtures, xdist, reruns and every pytest plugin. For Playwright Python projects pytest-bdd is usually the better fit.
🤔 Can I generate a Cucumber JSON report?
Yes: pytest --cucumberjson=reports/cucumber.json. Many CI and reporting tools read that format. Allure also shows pytest-bdd scenarios with their steps (Lesson 64).
🤔 Can steps use page objects?
Yes, and they should in larger suites: create page objects in fixtures (Lesson 56) and call them from step definitions, so locators stay out of steps.
🤔 How do I run one scenario?
Use -k with part of the scenario name (pytest -k "Successful login"), or select the generated test by node id from --collect-only output.
🤔 What changed in recent pytest-bdd versions?
pytest-bdd 8 and 9 use the official Gherkin parser, pass data tables through the datatable fixture and doc strings through docstring, and substitute Scenario Outline values directly into step text (parsed like any other value). Old tutorials using example_converters or <param> fixtures no longer apply.
🏁 Summary
- BDD describes behaviour as Gherkin scenarios; pytest-bdd runs them as pytest tests with Playwright fixtures.
- Write steps with
@given/@when/@thenandparsers.parse, bind features withscenarios(), and share common steps inconftest.py. - Scenario Outlines run once per Examples row; data tables arrive in the
datatablefixture;target_fixturepasses state between steps. - Tags become markers (
-m smoke),--strict-markerscatches tag typos, and--generate-missingwrites step skeletons. - Keep scenarios declarative and behaviour-focused; use BDD where non-testers read the scenarios.
🎬 Watch the Playwright tutorial series on YouTube!
Subscribe to SqaToolsByDY • Practice on the SQA Tools Automation Practice Page