Skip to content

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 dashboard
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 dashboard

Example 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):
    pass
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):
    pass

Tips

  • 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 coffee

Was this page helpful?

Let us know how we did