Next-Gen App & Browser
Testing Cloud

Trusted by 2 Mn+ QAs & Devs to accelerate their release cycles

Next-Gen App & Browser Testing Cloud
  • Automation
  • Home
  • /
  • Learning Hub
  • /
  • Gherkin Testing: A Detailed Guide on Writing Gherkin Tests

Gherkin Testing: A Detailed Guide on Writing Gherkin Tests

Learn how to perform Gherkin testing with this comprehensive guide. Master syntax, scenarios, and best practices for clear, behavior-driven testing.

Published on: September 3, 2025

  • Share:

Gherkin testing is the process of writing and executing tests using the Gherkin language, which is a plain-text, structured format for describing software behavior. It is most commonly used with Behavior-Driven Development (BDD) frameworks like Cucumber or Behave.

Overview

In testing, Gherkin is a simple, structured language used to write test cases in a way that’s easy for both technical and non-technical people to understand.

Syntax of Gherkin File

Feature: User login
  Scenario: Successful login with valid credentials
    Given the user is on the login page
    When the user enters valid credentials
    Then the user should be redirected to the dashboard

Core Keywords and Their Applications

  • Feature: Describes the functionality being tested, giving context at a high level.
  • Scenario: Defines a single path of behavior to be validated.
  • Given: Sets the initial context or state before actions occur.
  • When: Describes an action performed by the user or system.
  • Then: States the expected outcome or result of the action.
  • And / But: Extend Given, When, or Then steps to keep scenarios readable and concise.
  • Background: Defines common preconditions that apply to all scenarios in a feature.
  • Examples: Supply test data for Scenario Outlines to cover multiple variations efficiently.

What Is Gherkin?

Gherkin is a plain-text language used to describe software behaviors in a way that’s both human-readable and structured enough for automated testing tools. It’s most commonly associated with frameworks like Cucumber for Behavior-Driven Development.

The main idea is to bridge communication between technical and non-technical team members. Instead of writing complex test scripts, you write simple scenarios that outline what the system should do in specific situations.

Syntax and Structure of Gherkin

A Gherkin file (usually ending in .feature) is organized into features, scenarios, and steps.

  • Feature: Describes the functionality under test.
  • Scenario: Represents a concrete example or test case for that feature.
  • Steps: Written in plain language with specific keywords that define behavior.

Example:


Feature: User login
  Scenario: Successful login with valid credentials
    Given the user is on the login page
    When the user enters valid credentials
    Then the user should be redirected to the dashboard

Keywords

Gherkin uses specific keywords to define the role of each line. These keywords can be localized into different languages.

  • Feature: High-level description of what is being tested.
  • Scenario: A single example or test case.
  • Given: Sets up initial context or preconditions.
  • When: Describes an action or event.
  • Then: States the expected outcome or result.
  • And / But: Used for step continuation to improve readability.
  • Background: Defines steps common to all scenarios in a feature.
  • Scenario Outline: Used for parameterized scenarios with different data sets.
  • Examples: Provides the data for a scenario outline.

Scenario Outline and Examples

For repetitive scenarios with different inputs, you use Scenario Outline and Examples.


Scenario Outline: Login attempts
  Given that the user is on the login page
  When the user enters "<username>" and "<password>"
  Then the system displays "<message>"

  Examples:
    | username | password | message            |
    | alice    | pass123  | Welcome, alice!    |
    | bob      | wrong    | Invalid credentials|

Comments

Use # at the start of a line for comments. They are ignored during execution.


# This is a comment about the scenario

Formatting and Indentation

Indentation is optional but recommended for readability. Consistent spacing makes large feature files easier to scan.

A common approach is to indent steps under their corresponding Scenario or Background so the structure is clear at a glance. For example, keeping all Given, When, and Then statements aligned under a scenario title helps distinguish them from higher-level keywords like Feature or Scenario Outline.

Note

Note: Run your Gherkin tests across 3000+ desktop browsers. Try LambdaTest Now!

Core Gherkin Keywords and Their Applications

In Gherkin, the language used to write BDD scenarios, keywords structure the specification so that it is easy to read, consistent, and executable by automation testing tools like Cucumber.

Here are the core Gherkin keywords and how they are applied:

Feature

  • Purpose: Introduces the high-level functionality being described.
  • Usage: Placed at the top of a .feature file to summarize the intent or scope.

Example:


Feature: User login
  Users should be able to log in with valid credentials

Scenario

  • Purpose: Defines a single concrete example or test case of the feature.
  • Usage: Follows the Feature section, describing a specific behavior through steps.

Example:


Scenario: Successful login with valid credentials

Given

  • Purpose: Sets the initial context or preconditions before an action occurs.
  • Usage: Often describes the starting state of the system or data.

Example:


Given the user is on the login page

When

  • Purpose: Specifies the action or event performed by the user or system.
  • Usage: Describes the trigger for the behavior being tested.

Example:


When the user enters valid credentials

Then

  • Purpose: Outlines the expected outcome or result.
  • Usage: Verifies that the system behaves as intended after the action.

Example:


Then the user should see the dashboard

And / But

  • Purpose: Adds additional conditions or steps without repeating Given, When, or Then.
  • Usage: Improves readability by chaining related steps.

Example:


And the welcome message is displayed
But the user does not see admin options

Background

  • Purpose: Defines common preconditions for all scenarios in a feature.
  • Usage: Reduces repetition by setting up shared Given steps.

Example:


Background:
Given the user is logged in

Scenario Outline

  • Purpose: Allows parameterized scenarios for multiple data sets.
  • Usage: Works with the Examples keyword to run the same scenario with varied inputs.

Example:


Scenario Outline: Login with multiple user roles
Given the user is on the login page
When the user logs in with <username> and <password>
Then the <role> dashboard is displayed

Examples:
| username | password | role   |
| alice    | pass123  | admin  |
| bob      | pass456  | member |

Examples

  • Purpose: Supplies the data table for Scenario Outlines.
  • Usage: Each row runs the scenario once with those values.

Advanced Gherkin Constructs

Beyond the core keywords, Gherkin has a few advanced constructs that help you make scenarios more expressive, reusable, and maintainable when working on larger test suites.

Here are the main ones and how they are used.

Tags

  • Purpose: Categorize or group features and scenarios for filtering in test execution.
  • Usage: Placed on the line above a Feature or Scenario. Can be used to run only certain tests (e.g., @smoke, @regression).

Example:


@smoke @login
Scenario: Successful login with valid credentials
Given the user is on the login page
When the user enters valid credentials
Then the user should see the dashboard

Doc Strings

  • Purpose: Allow multi-line text to be passed as input to a step without breaking formatting.
  • Usage: Enclosed in triple quotes """. Often used for JSON, XML, or plain text bodies.

Example:


When I send the following payload:
"""
{
  "username": "alice",
  "password": "pass123"
}
"""

Data Tables

  • Purpose: Pass structured data to a step in a readable way.
  • Usage: Each row represents related values, like a spreadsheet. Used for inputs, configuration, or expected results.

Example:


Given the following users exist:
| name  | role   | active |
| Alice | admin  | true   |
| Bob   | member | false  |

Rule

  • Purpose: Group related scenarios within a feature and state a business rule they cover.
  • Usage: Improves organization and clarifies intent in long feature files.

Example:


Rule: Only active members can log in
Scenario: Active user logs in successfully
Scenario: Inactive user is denied access

Background with Multiple Contexts

  • Purpose: Combine Background with Rules to create more localized shared steps.
  • Usage: Each Rule can have its own Background to avoid unrelated steps in other scenarios.

Parameterized Steps (Step Definitions)

  • Purpose: Write flexible steps that accept variables.
  • Usage: The Gherkin step contains placeholders like "([^"]*)" or <value>, depending on the BDD tool.

Example:


When the user logs in with username "alice" and password "pass123"

Conjunctions in Nonlinear Ways

  • Purpose: Mix And and But in Given, When, and Then blocks to describe complex behavior.
  • Usage: Allows chaining without repeating main keywords, but keep readability in mind.

Hooks Integration (Tool-Specific)

  • Purpose: Although not Gherkin syntax itself, hooks in Cucumber tie into Gherkin scenarios to run setup or teardown code before/after scenarios, features, or tagged groups.
  • Usage: Triggered via tags or lifecycle events.

How to Perform Gherkin Testing With Selenium?

Let’s look at the simple Gherkin test written using Selenium and Cucumber that validates the login functionality of LambdaTest eCommerce Playground.

Here is the Gherkin feature file:


Feature: User Login

  Scenario: Login with valid credentials
    Given the user is on the login page
    When the user enters valid credentials
    And clicks on the login button
    Then the user should be logged in successfully

Below is the test script for the step definitions written using Selenium Cucumber:


package steps;

import io.cucumber.java.en.*;
import org.openqa.selenium.*;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import java.net.MalformedURLException;
import java.net.URL;
import java.time.Duration;

public class LoginSteps {
    WebDriver driver;

    @Given("the user is on the login page")
    public void the_user_is_on_the_login_page() throws MalformedURLException {
        ChromeOptions options = new ChromeOptions();
        driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), options);
        driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
        driver.get("https://ecommerce-playground.lambdatest.io/index.php?route=account/login");
    }

    @When("the user enters valid credentials")
    public void the_user_enters_valid_credentials() {
        driver.findElement(By.id("input-email")).sendKeys("testuser@example.com");
        driver.findElement(By.id("input-password")).sendKeys("Password123");
    }

    @When("clicks on the login button")
    public void clicks_on_the_login_button() {
        driver.findElement(By.cssSelector("input[value='Login']")).click();
    }

    @Then("the user should be logged in successfully")
    public void the_user_should_be_logged_in_successfully() {
        String heading = driver.findElement(By.cssSelector("h2")).getText();
        if (!heading.contains("My Account")) {
            throw new AssertionError("Login failed. Expected My Account page.");
        }
        driver.quit();
    }
}

Code Walkthrough:

  • Setup RemoteWebDriver: Initializes a remote Chrome browser session by connecting to a Selenium Grid hub running locally at http://localhost:4444/wd/hub with basic ChromeOptions.
  • Navigate and Wait: Opens the login page URL and sets an implicit wait of 10 seconds to allow elements time to appear before throwing exceptions.
  • Perform Login Actions: Enters predefined valid email and password into the login form fields and clicks the login button to submit.
  • Verify and Cleanup: Checks if the landing page contains the expected “My Account” heading to confirm successful login, then closes the browser session by quitting the driver.

Here is how each step in the Gherkin feature file is implemented in the Selenium script during Cucumber testing:

  • Given the User is on the Login Page: It opens a remote browser session via Selenium Grid and navigates to the login page URL, setting up the test’s starting point.
  • When the User Enters Valid Credentials: It simulates the user typing their email and password into the login form fields.
  • When the User Enters Valid Credentials: It simulates the user typing their email and password into the login form fields.
  • When the User Enters Valid Credentials: It simulates the user typing their email and password into the login form fields.
  • When Clicks on the Login Button: The code performs the action of clicking the login button to submit the form.
  • Then the User Should be Logged in Successfully: It verifies that the page shows the “My Account” heading, confirming the login succeeded, and then closes the browser.

For more information, check this guide on Selenium testing using Gherkin.

How to Perform Gherkin Testing With LambdaTest Online Selenium Grid?

Cloud testing platforms such as LambdaTest provides an online Selenium Grid that lets you run Gherkin-based BDD tests at scale across 3000+ real browsers and devices.

With LambdaTest, you can perform Selenium test automation using Cucumber, helping teams validate user stories in plain English while ensuring cross-browser compatibility. This reduces hassles of setting up test infrastructure and accelerates feedback in Agile workflows.

To perform Gherkin testing on LambdaTest, you only need to point your WebDriver to LambdaTest remote grid and configure the automation capabilities. You can generate capabilities from the LambdaTest Automation Capabilities Generator.


ChromeOptions browserOptions = new ChromeOptions();
browserOptions.setPlatformName("Windows 10");
browserOptions.setBrowserVersion("dev");
HashMap<String, Object> ltOptions = new HashMap<String, Object>();
ltOptions.put("username", "Your LambdaTest Username");
ltOptions.put("accessKey", "Your LambdaTest Access Key");
ltOptions.put("project", "Gherkin Testing With Selenium");
ltOptions.put("w3c", true);
ltOptions.put("plugin", "java-testNG");
browserOptions.setCapability("LT:Options", ltOptions);

Then, replace your LT_USERNAME and LT_ACCESS_KEY with actual values (or set them as environment variables).

Your .feature files and Gherkin scenarios remain unchanged, since LambdaTest only affects the execution environment, not the test logic.

To get started, refer to this guide on Selenium Cucumber testing on LambdaTest.

...

Best Practices for Writing Effective Gherkin Scenarios

Here are some of the best practices for writing effective Gherkin scenarios that are both readable and maintainable.

  • Keep Scenarios Focused on One Behavior: Each scenario should describe a single, specific behavior of the system. If you find yourself describing multiple variations, create separate scenarios. This keeps them easy to read, understand, and troubleshoot.
  • Use the “Business Language” of Your Stakeholders: Write steps using domain-specific terms that business stakeholders understand. Avoid implementation details like database fields or UI element IDs.
    • Instead of: Given the user clicks the Submit button
    • Prefer: Given the customer submits the order
  • Be Explicit but Concise: Write clear, unambiguous steps, but avoid clutter. A scenario should typically be 3-7 lines long. If it’s much longer, break it up into smaller ones.
  • Use Background Wisely: If multiple scenarios share the same setup, put it in a Background section to avoid repetition. Keep it short, since long backgrounds can make tests harder to understand.
  • Avoid Technical or UI Fragility: Do not tie your steps to UI details that may change often.
    • Instead of: When the user clicks the blue "Add" button
    • Use: When the user adds a new item
  • Name Scenarios Clearly: A scenario title should communicate intent, not implementation.
    • Bad: Scenario: Clicking the save button
    • Good: Scenario: Saving a draft when the form is partially complete
  • Use Tables for Data-Driven Steps: For repetitive steps with different inputs, use Gherkin’s Scenario Outline and examples table. This reduces duplication and makes patterns obvious.
  • Avoid Over-Specifying Flows: Capture the essence of the behavior, not every click or screen transition. Gherkin is for what should happen, not how it’s implemented.
  • Keep Scenarios Testable and Independent: Each should be runnable in isolation without relying on the state left behind by previous scenarios. This supports parallel execution and improves reliability.

If you are using Cucumber, you can follow these Cucumber best practices to write effective Gherkin scenarios.

Common Challenges in Gherkin Testing and Solutions

Here are the common challenges teams face with Gherkin testing, along with practical solutions to address them.

  • Overly Technical Language: Scenarios end up filled with implementation details (CSS selectors, database IDs, API endpoints) that non-technical stakeholders cannot follow.

    Solution: Use domain language that reflects business processes. Agree on a shared vocabulary with stakeholders and use it consistently across all scenarios.

  • Scenarios Becoming Too Long or Complex: Some scenarios try to cover multiple paths, edge cases, and actions in one script, making them hard to maintain.

    Solution: Break them into smaller, focused scenarios. One scenario should test one behavior. Use Scenario Outline for variations instead of cramming everything into one.

  • Background Sections Misused: Background steps become bloated with too much setup, leading to confusion about what’s actually relevant.
  • Solution: Keep backgrounds minimal and only for truly shared, stable setup steps. Any scenario-specific setup should remain in that scenario.

  • Fragile Steps Tied to UI Details: Tests fail frequently because they reference specific UI elements that change often.

    Solution: Write steps at a higher level of abstraction, describing actions in business terms. Let automation code handle the translation to UI interactions.

  • Duplicate or Inconsistent Steps: Different team members write similar steps in slightly different ways, creating redundancy.

    Solution: Maintain a shared step library and review new steps for reusability before adding them. This keeps the step set small and easier to maintain.

  • Ambiguity in Expected Outcomes: “Then the user should see the order” is vague. Does it mean in a table, in a confirmation message, or both?

    Solution: Be precise about the observable result while keeping the business perspective. For example, “Then the order appears in the pending orders list.”

  • Over-Reliance on Gherkin for All Testing: Teams try to capture every single Gherkin test case, including low-level checks, which bloats the suite.

    Solution: Use Gherkin for high-value, business-facing behaviors. Keep unit and integration tests in code where they belong.

  • Flaky Tests from Environment or Data Issues: Scenarios fail intermittently because of unstable test environments or inconsistent data states.

    Solution: Ensure test data is reset between runs and use stable, dedicated environments for acceptance testing.

  • Lack of Maintenance Over Time: As the application evolves, scenarios become outdated and no longer match the real business process.

    Solution: Schedule regular scenario reviews. Treat Gherkin scripts as living documentation, not write-once artifacts.

Conclusion

Gherkin provides a clear and structured way to describe software behavior in plain language while keeping scenarios directly tied to automated tests. By understanding its syntax, keywords, and advanced constructs, teams can write feature files that are both readable and executable. When combined with Selenium, Gherkin becomes a powerful bridge between business requirements and technical implementation, ensuring test coverage aligns with real-world use cases.

Following best practices helps maintain consistency and scalability, while awareness of common challenges prepares teams to resolve issues before they become blockers. In the end, effective use of Gherkin testing fosters better collaboration, improves test automation efficiency, and enhances overall software quality.

Frequently Asked Questions (FAQs)

What is Gherkin in testing?
Gherkin is a plain-text language used in BDD to define test scenarios in a way that is understandable for both technical and non-technical team members. It follows a structured format to describe the behavior of software, making test cases clear, readable, and easy to maintain.
How does Gherkin relate to Cucumber testing?
Gherkin is the language used by Cucumber to execute automated BDD tests. In Cucumber, feature files written in Gherkin describe test scenarios, and the tool maps each step to underlying code to run the tests. This integration allows teams to automate testing while keeping scenarios human-readable.
What are the advantages of using Gherkin software testing?
Gherkin improves collaboration between developers, testers, and business stakeholders because the tests are written in plain language. It ensures consistency in test documentation and supports automated testing with tools like Cucumber. Additionally, Gherkin makes test scenarios reusable and easier to maintain over time.
Which tools can be used for Gherkin testing?
Although Gherkin is a syntax rather than a tool, it is supported by many automation frameworks. Popular options include Cucumber for general BDD, SpecFlow for .NET applications, Behave for Python, and Behat for PHP. These Gherkin testing tools allow teams to run automated tests based on Gherkin scenarios.
Can non-technical team members write Gherkin test cases?
Yes, Gherkin is designed to be readable by anyone. Using simple keywords like Given, When, Then, And, and But, non-technical users such as business analysts or product owners can write and review test cases without needing coding knowledge.
How does Gherkin testing improve collaboration?
By using plain language to describe test scenarios, Gherkin ensures that everyone on the team, from developers to business stakeholders, can understand and contribute. This shared understanding reduces miscommunication and helps align development with business requirements.
Is Gherkin only for automated testing?
Not necessarily. While Gherkin is widely used with automation tools like Cucumber, it can also serve as a structured format for documenting manual test cases. Its main purpose is to create clear, understandable tests that improve communication between team members.
What makes Gherkin scenarios readable and structured?
Gherkin uses a step-based approach, where each scenario describes a situation, an action, and an expected result. This structured format ensures that test cases are easy to read, follow, and verify, reducing ambiguity in testing.
How does Gherkin support BDD?
Gherkin bridges the gap between business requirements and technical implementation by allowing test scenarios to be written in plain language. These scenarios can then be automated or reviewed, ensuring that software behavior aligns with business expectations.
Can Gherkin be used across different programming languages?
Yes, Gherkin is language-agnostic. Tools like Cucumber, Behave, and Behat support Gherkin for automation in multiple programming languages, making it versatile for teams working in different tech stacks.

Did you find this page helpful?

Helpful

NotHelpful

More Related Hubs

ShadowLT Logo

Start your journey with LambdaTest

Get 100 minutes of automation test minutes FREE!!

Signup for free