Writing Lettuce Step Definitions: Python Patterns
Step definitions are where your Gherkin scenarios connect to executable Python code. Getting them right means cleaner tests, less duplication, and fewer fragile regex patterns. This post covers the mechanics and patterns that hold up at scale.
The @step Decorator
Every step definition uses the @step() decorator from the lettuce module. The argument is a Python regex that matches against the text in your feature file:
from lettuce import step
@step('I click the login button')
def click_login(step):
# step argument is the Step object, not the scenario
passThe function always receives a step object as its first argument. The step object carries the raw step text and any multiline data (more on that later).
Capturing Parameters with Regex Groups
Use capturing groups to extract values from step text:
@step('I set the timeout to (\d+) seconds')
def set_timeout(step, seconds):
config.timeout = int(seconds)@step('I fill in "([^"]*)" with "([^"]*)"')
def fill_field(step, field_name, value):
world.form[field_name] = valueEach capturing group becomes a positional argument after step. Groups are always strings, so cast them explicitly.
For optional text, use (?:...):
@step('I (?:click|press) the "([^"]*)" button')
def click_button(step, button_label):
page.find_button(button_label).click()The world Object
world is a module-level object shared across all step definitions within a scenario run. Import it from lettuce:
from lettuce import world
@step('I have a logged-in user')
def create_user(step):
world.user = User.objects.create_user('testuser', password='pass')
world.client = Client()
world.client.login(username='testuser', password='pass')
@step('I visit my profile page')
def visit_profile(step):
world.response = world.client.get(f'/users/{world.user.pk}/')world is reset between scenarios, so state set in one scenario does not leak into the next. It is not reset between steps within the same scenario.
Do not use global variables or module-level state as a substitute for world. The reset behavior is what makes scenarios independent.
Multiline Step Data
Steps can carry a multiline string body, accessed via step.multiline:
Given the request body is:
"""
{
"name": "Alice",
"role": "admin"
}
"""import json
from lettuce import step, world
@step('the request body is:')
def set_request_body(step):
world.body = json.loads(step.multiline)And table data via step.hashes (list of dicts, one per row):
Given the following users exist:
| username | email | role |
| alice | alice@example.com | admin |
| bob | bob@example.com | user |@step('the following users exist:')
def create_users(step):
for row in step.hashes:
User.objects.create_user(
username=row['username'],
email=row['email'],
)Before and After Hooks
Hooks run before or after scenarios, features, or the entire suite. Import them from lettuce:
from lettuce import before, after, worldScenario-level hooks
@before.each_scenario
def setup_scenario(scenario):
world.errors = []
world.responses = []
@after.each_scenario
def teardown_scenario(scenario):
if hasattr(world, 'browser'):
world.browser.delete_all_cookies()Feature-level hooks
@before.each_feature
def setup_feature(feature):
print(f"\nStarting feature: {feature.name}")
@after.each_feature
def teardown_feature(feature):
cleanup_test_database()Suite-level hooks
@before.all
def setup_suite():
world.browser = start_browser()
@after.all
def teardown_suite():
world.browser.quit()Organizing Step Files
Lettuce loads all Python files inside features/steps/. Split step definitions by domain rather than by feature file:
features/steps/
auth_steps.py # login, logout, session
form_steps.py # fill in, submit, validation
api_steps.py # HTTP requests, response assertions
database_steps.py # ORM-level given/then stepsThis way, steps are reusable across feature files without duplication. A step defined in form_steps.py can be used in both registration.feature and checkout.feature.
Avoiding Fragile Patterns
Problem: overly specific regexes
# Bad — only matches this exact phrasing
@step('I click on the blue submit button on the registration form')Better: capture the variable part
# Good — reusable across any button
@step('I click the "([^"]*)" button')
def click_button(step, label):
page.click_button(label)Problem: assertions buried in setup steps
# Bad — mixes setup with assertion
@step('I create a user and the count should increase')Split setup (Given) and assertion (Then) into separate steps. One step, one responsibility.
Step Reuse Across Features
If the same step text appears in multiple feature files, define it once. Lettuce will match it wherever it appears, as long as the step file is in the steps/ directory. You do not need to import steps explicitly.
The one edge case: if two step files define a step with the same or overlapping regex, Lettuce will raise an ambiguity error. Keep step text distinct or make regexes non-overlapping.
A good next practice is building a shared steps/common_steps.py that holds generic steps like "I wait N seconds" or "the response status should be 200", and keeping domain-specific logic out of it.