Q2 of 21 · BDD / Cucumber
Explain the Given / When / Then structure in Gherkin and what each keyword means.
Short answer
Short answer: Given sets up the precondition (context), When describes the action the user or system takes, Then asserts the expected outcome. And / But extend any of the three without repeating the keyword.
Detail
Gherkin scenarios follow a narrative structure modelled on user stories:
Scenario: Successful login with valid credentials
Given the user is on the login page
And the user has a registered account with email "alice@example.com"
When the user enters valid credentials and clicks "Log in"
Then the user is redirected to the dashboard
And a welcome message "Hello, Alice" is displayed
Given — establishes the system state before the action. Think "context." Typically maps to test setup (navigating to a page, inserting DB rows, mocking an API).
When — the trigger — a user action, API call, or system event. There should usually be one When per scenario. Multiple Whens in a single scenario often signal that you have two scenarios collapsed into one.
Then — the observable outcome. Assertions go here. It should describe what the user sees or what the system state is, not internal implementation details.
And / But — grammatical sugar. "And" continues the previous keyword's intent; "But" adds a contrasting condition:
Then the order is placed successfully
But the discount code is not redeemed twice
Good practice: Scenarios should read like a specification, not a test script. Avoid implementation details ("When the user clicks the button with id='submit-btn'") — write what, not how.
// EXAMPLE
Feature: Shopping cart checkout
Scenario: Guest checkout with valid card
Given the cart contains 1 item priced at £29.99
When the user completes checkout with a valid Visa card
Then an order confirmation email is sent to the user
And the order status is "confirmed"
And the inventory count for that item decreases by 1