Writing Tests in Gherkin (Given-When-Then)
Gherkin structure
A .feature.feature file contains:
- Feature
- Scenario
- Steps (Given/When/Then)
Example feature
login.feature
Feature: Login
As a registered user
I want to login
So that I can access my account
Scenario: Valid login
Given I am on the login page
When I login with username "alice" and password "secret"
Then I should see the dashboardlogin.feature
Feature: Login
As a registered user
I want to login
So that I can access my account
Scenario: Valid login
Given I am on the login page
When I login with username "alice" and password "secret"
Then I should see the dashboardExample step definition
steps/login_steps.py
from behave import given, when, then
@given("I am on the login page")
def step_open_login(context):
# open browser or call app
pass
@when('I login with username "{username}" and password "{password}"')
def step_login(context, username, password):
pass
@then("I should see the dashboard")
def step_dashboard(context):
passsteps/login_steps.py
from behave import given, when, then
@given("I am on the login page")
def step_open_login(context):
# open browser or call app
pass
@when('I login with username "{username}" and password "{password}"')
def step_login(context, username, password):
pass
@then("I should see the dashboard")
def step_dashboard(context):
passTips
- Keep steps reusable
- Donβt put too many details in Gherkin
- Use Gherkin for business behavior, not technical design
If this helped you, consider buying me a coffee β
Buy me a coffeeWas this page helpful?
Let us know how we did
