PRACTICAL GUIDE / Gherkin syntax guide

Gherkin Syntax Guide: Given When Then with Examples

Use this Gherkin syntax guide to write clear Feature, Scenario, Given, When, Then, Background, Examples, and Data Table specs for practical QA teams.

By The Testing AcademyUpdated July 10, 20269 min read
All field guides
In this guide9 sections
  1. Start with one business rule and one example
  2. Use Feature, Rule, and Scenario as a hierarchy
  3. Make Given, When, and Then carry distinct meaning
  4. Parameterize examples without turning them into spreadsheets
  5. Pass structured data with tables and doc strings
  6. Keep Background short and visible
  7. Use tags and comments as operational metadata
  8. Connect steps to automation without duplicating language
  9. Review feature files as executable specifications

What you will learn

  • Start with one business rule and one example
  • Use Feature, Rule, and Scenario as a hierarchy
  • Make Given, When, and Then carry distinct meaning
  • Parameterize examples without turning them into spreadsheets

Three people agreed that a suspended customer “cannot place an order.” The analyst meant the checkout button should be disabled, the developer returned HTTP 403 after submission, and the tester expected the cart to remain unchanged. Their Gherkin scenario repeated the sentence but settled none of those differences. Good syntax matters, but concrete examples and observable outcomes are what turn a feature file into a shared specification.

Start with one business rule and one example

A feature file should describe behavior that a product stakeholder recognizes. It is not a screenplay for clicks or a wrapper around test code. Before writing keywords, state the rule in plain language and find an example that could disprove it.

GHERKIN
Feature: Ordering restrictions
  Customers whose accounts are suspended must not create new orders.

  Scenario: Suspended customer submits a valid cart
    Given Maya has a suspended customer account
    And her cart contains one in-stock keyboard
    When Maya submits the cart
    Then the order is rejected because the account is suspended
    And her cart still contains the keyboard

The scenario names the relevant state, action, reason, and retained cart state. It avoids interface details, so the team can automate it through an API today and keep the specification if the UI changes tomorrow.

Keep each scenario focused on a single rule. Multiple When steps often signal that two behaviors have been combined. A later When can also make it unclear which action produced the result.

Use Feature, Rule, and Scenario as a hierarchy

Feature gives the capability and its purpose. A .feature file has one Feature. Free-form description lines below it can explain scope or business value without becoming executable steps.

Rule groups examples that demonstrate one business rule. It is valuable when a capability has distinct policies, such as account restrictions and stock restrictions. Scenario and Example are equivalent keywords for a concrete case.

GHERKIN
Feature: Order acceptance
  The store accepts only orders it can legally and operationally fulfill.

  Rule: Suspended accounts cannot order
    Scenario: Suspended account has a valid cart
      Given a suspended customer has an in-stock item in the cart
      When the customer submits the cart
      Then no order is created

  Rule: Active accounts can order available stock
    Scenario: Active account has sufficient credit
      Given an active customer has an in-stock item in the cart
      And the customer has sufficient credit
      When the customer submits the cart
      Then an order is created for the item

Do not organize files by page name merely because automation uses pages. Organize around product capabilities and rules. That keeps discussions stable as screens move.

Make Given, When, and Then carry distinct meaning

Given establishes state that is true before the behavior. When describes the event under examination. Then describes an observable result. And and But continue the preceding keyword's meaning.

A common weak scenario reads like this:

GHERKIN
Scenario: Login
  Given I open the login page
  When I enter "maya@example.test"
  And I enter "correct-password"
  And I click login
  Then I see the dashboard

It binds the specification to controls and hides the important precondition. A stronger version expresses the authentication rule:

GHERKIN
Scenario: Active customer authenticates with valid credentials
  Given Maya has an active account
  When Maya signs in with her valid credentials
  Then a new authenticated session is created for Maya

The step implementation may still use a browser, but the feature remains readable to someone who does not know its selectors. Use domain verbs such as “submits the cart” and “approves the refund.” Avoid vague verbs such as “processes it” when several actions could match.

Then steps should not introduce hidden state. “Then the order status is shipped” is observable. “Then the database row has status 7” exposes an implementation detail unless that database contract is specifically being tested.

Parameterize examples without turning them into spreadsheets

A Scenario Outline runs once for every row in its Examples table. Angle-bracket placeholders can appear in the name, steps, descriptions, and data arguments.

GHERKIN
Scenario Outline: Discount is selected from customer tier
  Given Priya has the <tier> customer tier
  And her cart subtotal is <subtotal>
  When the cart total is calculated
  Then the discount is <discount>

  Examples: eligible tiers
    | tier   | subtotal | discount |
    | silver | 100.00   | 5.00     |
    | gold   | 100.00   | 10.00    |

Use outlines when the behavior is structurally identical and only business values vary. Do not place every boundary permutation into a feature file. Detailed numeric combinations are often clearer and faster in unit tests. The feature should preserve representative examples that helped the team agree on the rule.

Name Examples blocks when categories matter, such as eligible tiers and ineligible tiers. A row should be understandable without reading code. Prefer domain values over flags like true and false.

Pass structured data with tables and doc strings

A data table supplies structured input to one step. It is not the same as an Examples table, which expands a Scenario Outline into several scenarios.

GHERKIN
Scenario: Order contains items from two warehouses
  Given the cart contains:
    | sku    | quantity | warehouse |
    | KB-104 | 1        | north     |
    | MS-220 | 2        | west      |
  When the customer submits the cart
  Then two fulfillment requests are created

Use a doc string for a larger text or payload where a table would distort the input. A media type after the opening delimiter can help tooling and readers.

GHERKIN
Scenario: Partner submits an invalid order payload
  When the partner submits this order:
    """json
    {
      "customerId": "C-19",
      "items": []
    }
    """
  Then the request is rejected with the reason "at least one item is required"

Keep transport details only when they are part of the contract under discussion. A partner API feature can name payloads and status codes. A customer-facing checkout feature usually should not.

Escape a literal pipe in a table cell as \|. Preserve indentation consistently because it makes nested structures readable even when the parser is permissive.

Keep Background short and visible

Background runs before each scenario in its Feature or Rule. It can remove repeated context, but it can also hide why a scenario behaves as it does.

GHERKIN
Feature: Refund approval

  Background:
    Given the store currency is GBP
    And refund approval is enabled

  Scenario: Supervisor approves a refund within authority
    Given a supervisor may approve refunds up to 500.00
    And a refund of 120.00 is awaiting approval
    When the supervisor approves the refund
    Then the refund is scheduled for payment

Limit Background to context that is true for nearly every scenario and important to understanding them. Avoid long setup sequences, user registration flows, or technical cleanup. If a reader must scroll upward to decode every example, repeat the key fact in the scenario instead.

Hooks in an automation framework are not Gherkin Background. Hooks handle technical concerns such as opening a browser or clearing a test tenant. Background expresses business context and should remain meaningful to collaborators.

Use tags and comments as operational metadata

Tags begin with @ and can be placed above Feature, Rule, Scenario, Scenario Outline, and Examples. They are inherited down the hierarchy. Use them for stable capabilities, ownership, or execution needs.

GHERKIN
@orders @api
Feature: Order cancellation

  @smoke
  Scenario: Customer cancels before packing begins
    Given an order is awaiting packing
    When the customer cancels the order
    Then the order is marked as cancelled

Avoid a tag taxonomy that mirrors every sprint, person, environment, and temporary defect. Expressions such as @smoke and not @quarantine are useful only if the team defines who owns each tag and when it is removed.

Comments start with #. Use them sparingly for information that cannot be expressed as behavior. Commented-out scenarios rot quickly and should be removed through version control instead.

Connect steps to automation without duplicating language

Step matching typically ignores the keyword, so Given the account is active and Then the account is active can collide. Write a consistent domain phrase and keep step definitions small. One step should coordinate domain helpers, not contain an entire end-to-end workflow.

Do not create synonyms for convenience. If “customer,” “shopper,” and “user” mean the same role, select one term in the product glossary. Ambiguous or duplicate step expressions make a suite unpredictable.

Automation is not mandatory for every scenario. A feature file can support discovery before code exists. Once automated, verify that a deliberately broken rule produces a failing scenario for the expected reason. Also confirm the runner fails on undefined and pending steps rather than reporting a misleading green build.

Review feature files as executable specifications

Review a scenario with three questions: What rule does this example demonstrate? Could a product stakeholder predict the result? Can the result be observed without reading the implementation? If any answer is unclear, better syntax will not rescue it.

During refinement, vary the example. Ask what changes at a boundary, what remains unchanged after rejection, and which actor can observe the result. These questions often expose missing rules before automation begins.

In repository review, check for duplicate scenarios, accidental UI language, oversized Background blocks, unbounded outlines, inconsistent terminology, and tags with no operating policy. Run the Gherkin parser in CI even for scenarios that are not automated, so malformed tables and missing Examples blocks fail quickly.

The final test is conversational: give the file to an analyst, developer, and tester, then ask each to explain the same outcome. When their explanations agree and the automated check proves that outcome at an appropriate boundary, Gherkin is doing useful work. When the file only narrates clicks, it is test code written in a more expensive syntax.

// FIELD DISPATCH

Get the QA Field Notes

Weekly QA battles, AI testing guides, and interview drills. Free on Substack.

// LIVE COURSE / THE TESTING ACADEMY

Playwright Automation Mastery

Go beyond Selenium. Master Playwright with JS/TS in 90 days.

From the instructor behind this guide.

Playwright jobs are growing 8x faster than Selenium. 90 days / 75+ live hrs / Tue-Thu-Sat 7 AM IST.

Code PROMODE / 10% offJoin the batch

The Testing Academy editorial desk

Practical QA guidance built around test evidence, production tradeoffs, and interview-ready explanations.

Published July 10, 2026 / Reviewed July 10, 2026

PRIMARY REFERENCES

Verify the details at the source

QABattle guides are practical explanations. Product behavior, standards, and APIs can change, so use these primary references for the canonical details.

  1. 01
    Gherkin reference

    Cucumber

    Official feature, scenario, rule, example, and step syntax.

  2. 02
    WebDriver standard

    W3C

    The browser automation protocol specification used by major automation stacks.

FAQ / QUICK ANSWERS

Questions testers ask

What distinct job should Given, When, and Then perform in Gherkin?

Given establishes relevant state before the behavior, When names the event being examined, and Then states an observable result. And and But continue the previous keyword's role. Prefer one principal When per scenario, keep hidden setup out of Then, and express domain actions rather than clicks so the specification survives interface changes.

How is a Scenario Outline different from a data table?

A Scenario Outline expands the whole scenario once for each Examples row, so it suits a few structurally identical business cases. A data table passes structured input to one step within one scenario. Keep exhaustive numerical permutations in faster code tests, and use doc strings when a larger text or payload would be distorted by a table.

When does a Gherkin Background become harmful?

Background is useful only for short business context shared by nearly every example in its Feature or Rule. Long setup flows force readers to scroll and conceal why an outcome occurs. Repeat a decisive fact in the scenario when clarity improves. Keep browser startup, tenant cleanup, and other technical lifecycle work in automation hooks instead.

Why can syntactically correct Gherkin still be a poor specification?

Keywords cannot resolve an ambiguous rule. A scenario that says a suspended customer cannot order may leave order creation, cart state, and rejection reason undefined. Start with a concrete example that could disprove the rule, name unchanged state as well as the primary result, and verify that product, development, and QA predict the same outcome.

What checks keep Gherkin automation maintainable?

Use a small shared domain vocabulary, avoid synonymous step expressions, and keep step definitions focused on coordinating helpers. Run the parser in CI, fail on undefined or pending steps, and deliberately break a rule to confirm the scenario turns red for the expected reason. Tags should have stable execution ownership rather than mirror temporary sprints or people.