ScreenshotNeo

BlogGuides

How to Write Gherkin Test Cases

Learn to write clear, maintainable Gherkin scenarios with Given, When, and Then, plus Scenario Outlines, step definitions, and a practical review checklist.

By the ScreenshotNeo team4 October 20268 min read

Write a Gherkin test case as a short example of one behavior: establish the starting context with Given, describe the event with When, and state an observable expected result with Then. For example:

Feature: Account withdrawals

  Scenario: Withdraw within the available balance
    Given an account has a balance of $100
    When the customer withdraws $25
    Then the account balance is $75

That text becomes an automated test only when a Cucumber runner can match its steps to step definitions that exercise the software and check the outcome. Gherkin is the structured language; Cucumber is one tool that reads it. Feature files are commonly saved as .feature files alongside the software in source control. They can also document expected behavior for the team. Cucumber’s introduction explains the relationship between Gherkin, feature files, and step definitions.

1. Start with one behavior and its outcome

Before writing syntax, agree on the behavior the example should describe. A useful scenario answers three questions:

  • Given: What relevant state is already true?
  • When: What event or action matters?
  • Then: What observable result should follow?

Keep the example about one behavior, such as a customer withdrawing money within their available balance. If it also tries to cover an overdraft, a declined card, and an audit report, split those into focused scenarios. Cucumber suggests three to five steps as a readability guide, not a syntax limit.

2. Use Given, When, Then, And, and But well

Given establishes context

Use Given to put the system in a known state before the event. For the withdrawal example, the account balance is the relevant context. Avoid putting the user’s interaction in a Given; the action belongs in When. The Gherkin reference describes Given steps as establishing a known state before interaction begins.

When describes the event

Use When for the meaningful action by a person or an external system. “When the customer withdraws $25” captures the business event without specifying how the customer operates a particular screen.

Then states an observable result

Use Then for an outcome that can be observed, such as the displayed balance, a confirmation message, or a generated report. The matching automation should assert the expected result. Prefer an observable product outcome to a deeply buried implementation detail that users and stakeholders cannot interpret.

And and But continue a step type

Use And or But to make additional steps easier to read:

Scenario: Withdraw within the available balance
  Given an account has a balance of $100
  And the account is active
  When the customer withdraws $25
  Then the account balance is $75
  And the customer receives a withdrawal confirmation

Cucumber uses the step text to match a step definition; the keyword itself does not make otherwise identical step text a different match. Avoid defining ambiguous steps that share the same wording under different keywords.

3. Prefer business language over interface choreography

A maintainable scenario describes application behavior rather than a sequence of implementation-specific operations. For example:

Scenario: Customer signs in with valid credentials
  Given the customer has an active account
  When the customer signs in with valid credentials
  Then the customer sees their account overview

A more procedural version might say to open a particular page, type into a named field, click a button, and inspect a specific element. That can be useful when the purpose is explicitly to test a UI interaction, but it couples the example to the current interface. If the login flow changes while the behavior stays the same, implementation-heavy wording may need edits. Cucumber’s guidance on writing better Gherkin recommends declarative language focused on behavior.

4. Organize a feature file

A feature file contains one Feature, which names a subject and groups related scenarios. A short description can follow the feature line. Use two-space indentation as a consistent convention.

Feature: Account withdrawals
  Customers can withdraw funds when their account has enough money.

  Rule: A withdrawal must not exceed the available balance

    Scenario: Withdraw within the available balance
      Given an account has a balance of $100
      When the customer withdraws $25
      Then the account balance is $75

A Rule groups scenarios that illustrate one business rule; it has been part of Gherkin since version 6. Keep rules and descriptions only when they help readers understand the behavior. A feature file should have a single Feature declaration.

5. Choose between Scenario and Scenario Outline

Scenario and Example are synonyms. Use a normal scenario for a concrete example. Use a Scenario Outline when the same behavior should be illustrated with several sets of data and the table makes those cases easy to review.

Feature: Account withdrawals

  Scenario Outline: Withdraw within the available balance
    Given an account has a balance of <starting balance>
    When the customer withdraws <amount>
    Then the account balance is <remaining balance>

    Examples:
      | starting balance | amount | remaining balance |
      | $100             | $25    | $75               |
      | $40              | $10    | $30               |

Each row after the Examples header produces a run, with the angle-bracket placeholders filled from that row’s columns. An outline needs at least one Examples section. Use separate scenarios when cases represent meaningfully different behavior or when the table obscures what each case means; there is no universal row-count threshold for choosing an outline.

6. Pass structured or longer data to a step

Use a data table when a step needs structured input, such as several products or account records. Use a doc string when a step needs a larger text argument, such as a message body or document.

Scenario: Register several products
  Given the following products are available:
    | name       | price |
    | Notebook   | 5.00  |
    | Pen        | 1.50  |
Scenario: Submit a support message
  When the customer submits this message:
    """
    I cannot access my account after changing my email address.
    """
  Then the support request is acknowledged

Doc strings can use triple double-quotes or triple backticks. Editor support for backticks can vary, so use the delimiter supported by the tools your team uses.

7. Connect Gherkin steps to automation

Gherkin is not executable by itself. In a Cucumber project, a runner loads feature files and step definitions. Each definition matches step text, performs the needed setup or action, or asserts the result. The exact setup commands, file layout, and definition syntax depend on the Cucumber implementation and programming language, so consult the documentation for the implementation and version in your project.

For each step, decide what the automation must do and what evidence proves success. For example, a Given might arrange an account with a known balance, a When might invoke the withdrawal behavior, and a Then might compare the observed account balance to the expected amount. Keep setup and assertion code in step definitions or supporting helpers rather than embedding code in the feature text. Review whether each step has a clear meaning and can be matched unambiguously.

Feature files can also serve as living documentation, but only when the examples stay meaningful and the automation remains connected to the behavior they describe. Collaborate with product, development, and testing teammates while establishing shared vocabulary. Cucumber’s collaboration guidance describes scenario writing as a shared activity, with continued product or business review.

8. Write maintainable scenarios: review checklist

  • Does the scenario describe one behavior?
  • Is each Given a relevant, well-defined starting fact?
  • Is the When the event that matters to the behavior?
  • Does the Then describe a result someone can observe?
  • Could the wording remain valid if the interface or internal implementation changed?
  • Does each step express one distinct fact or action?
  • Does the team use the same phrase for the same domain meaning?
  • Can the step text be understood by the team and matched to automation?
  • Would an outline table make repeated cases clearer, or would separate scenarios be easier to understand?

Split steps that bundle unrelated actions or facts. Prefer consistent domain terms over synonyms that mean the same thing. If a scenario needs many steps to explain the behavior, consider whether it contains multiple behaviors or too much setup detail.

Or skip the browser setup

For a screenshot of a page used in a test plan, bug report, or acceptance review, ScreenshotNeo is a website screenshot API and MCP server for developers. It can return a PNG, JPEG, WebP, or PDF from one GET request. This does not replace writing Gherkin scenarios or connecting them to Cucumber step definitions; it can provide a page capture when your workflow needs one.

cURL:

curl -G "https://api.screenshotneo.com/v1/shot" \
  -d access_key=YOUR_API_KEY \
  --data-urlencode url=https://stripe.com \
  -o shot.webp

Python:

import requests

r = requests.get(
    "https://api.screenshotneo.com/v1/shot",
    params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"},
    timeout=90,
)
open("shot.webp", "wb").write(r.content)

Node.js:

const q = new URLSearchParams({
  access_key: 'YOUR_API_KEY',
  url: 'https://stripe.com',
});
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`Screenshot request failed: ${res.status}`);
await require('node:fs/promises').writeFile('shot.webp', Buffer.from(await res.arrayBuffer()));

See the ScreenshotNeo API documentation for request options. Cookie banners are accepted and removed before capture, along with known consent platforms, newsletter popups, and chat widgets; each cleanup step can be turned off. Bot checks, blank pages, failed loads, timeouts, and cache hits cost nothing, and response headers identify the page verdict and billing status. An MCP server provides take_screenshot, get_page_info, and capture_pdf tools for AI agents and MCP clients. The free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000 screenshots.

Sign up for 1,000 free screenshots a month, with no card required.

Common Gherkin mistakes and fixes

Problem Why it hurts Fix
The scenario is only plain text with no automation Gherkin syntax does not execute behavior on its own. Configure a Cucumber runner and implement matching step definitions that exercise and assert the behavior.
The Then checks a hidden implementation detail Readers may not know what the assertion means, and internal changes can break the scenario without changing behavior. Assert an observable result such as a message, report, or user-visible state where appropriate.
Every step describes clicks and fields The scenario is coupled to the current UI and can become costly to maintain. Describe business behavior declaratively; retain interface detail when the interface interaction itself is the behavior under test.
One scenario covers several unrelated outcomes It is hard to identify which behavior failed and difficult to review. Split distinct actions, rules, or outcomes into focused examples.
Two steps have the same text but different keywords Step matching is based on text, so definitions can be ambiguous. Use clear, distinct step wording and check definitions for collisions.
An outline has placeholders but no Examples table The outline has no data rows from which to create runs. Add an Examples section with a header matching every placeholder and one or more data rows.
Terms shift from scenario to scenario Inconsistent vocabulary makes shared meaning and step reuse harder. Agree on domain language and use the same wording for the same meaning.

FAQ

Is Gherkin a programming language?

Gherkin is a structured language for describing examples of behavior. It is not the implementation of the application or the step-definition code that automates those examples.

Can a feature file contain multiple features?

No. A Gherkin feature file contains one Feature. Group related scenarios under that feature and use separate files for separate features.

How do I write a feature file in another spoken language?

The default language is English unless the Cucumber implementation configures another default. A first-line # language: header can select a Gherkin language. Check the reference and implementation version for supported keywords and configuration.

How many steps should a scenario have?

Three to five is Cucumber’s readability suggestion, not a hard limit. Use the smallest number that explains the context, event, and observable outcome clearly.

References