Exploring Gherkin Syntax

6 minutes read

Gherkin is the cornerstone of Cucumber, a Behavior-Driven Development (BDD) framework. It’s a domain-specific language (DSL) that uses plain text and simple keywords. The goal? Make software requirements clear to everyone, from developers to business stakeholders.

By keeping a consistent format, Gherkin bridges the gap between what the business needs and what the code tests. Your .feature files become living documentation—easy to read, easy to update, and directly linked to automated tests.

In this guide, we’ll dive into Gherkin syntax in detail, explain how it works, and show you real examples you can use right away

What is Gherkin?

Gherkin is not a programming language. Instead, it’s a way to write test scenarios in a structured, natural-language style. You save these scenarios in files ending with .feature.

Each file contains descriptions that double as both specifications and executable tests. That’s why we call them living documentation: they grow and stay current as your application evolves.

One great feature of Gherkin syntax is its language-agnostic. While English is most common, you can write in French, Spanish, or any supported language. This flexibility helps teams around the world collaborate in their native tongue.

Core Keywords and Structure

Gherkin relies on a handful of main keywords. Each one plays a clear role in your feature file, ensuring Gherkin syntax remains easy to understand:

Core Keywords and Structure of Gherkin Syntax

Feature

  • Purpose: Names the feature or requirement you’re testing.
  • Syntax: Feature: [Title]
  • Description: A few lines (optional) under the title, formatted like:

    As a [role], I want [goal], so that [benefit]

Feature: User Authentication
 
  As a registered user
 
  I want to log in securely
 
  So that I can access my dashboard

Scenario

  • Purpose: Defines a single test case or example.
  • Syntax: Scenario: [Scenario title]

Each scenario should test one behavior. If you have multiple flows, split them into separate scenarios.

Scenario: Successful login with valid credentials

Given, When, Then

These three keywords form the core of every scenario:

  • Given: Sets up the initial context or preconditions.
    • Example: Given the user is on the login page
  • When: Describes the action or event.
    • Example: When the user enters valid credentials
  • Then: States the expected outcome.
    • Example: Then the user should see the dashboard

Use each keyword once per scenario. If you need extra steps, use And or But.

And / But

  • Purpose: Extends or contrasts the previous step without repeating keywords.
  • Syntax: Placed after a Given, When, or Then.
Given the user is on the login page
 
And the login form is visible
 
When the user enters "alice" and "password123"
 
And clicks the login button
 
Then the dashboard appears
 
But no error message is shown

Use And to continue in the same flow. Use But to highlight an exception.

Advanced Gherkin Constructs

Beyond the basics, Gherkin gives you tools to avoid repetition and handle complex scenarios:

Scenario Outline

Purpose: Test the same scenario with different data sets.

Syntax: Use Scenario Outline: with placeholders <variable> and an Examples table.

Scenario Outline: Login attempts with various credentials
 
  Given the user is on the login page
 
  When the user enters "<username>" and "<password>"
 
  Then the result should be "<message>"
 
Examples:
 
  | username | password | message         |
 
  | user1    | pass1    | Login successful|
 
  | user2    | wrong    | Invalid password|

Cucumber runs the scenario once per row, substituting values automatically.

Background

Purpose: Define shared preconditions for every scenario in a feature.

Syntax: Place a Background: section before your scenarios.

Feature: Shopping Cart Management
 
  Background:
 
    Given the user is logged in
 
    And the cart is empty
 
  Scenario: Add a product to the cart
 
    When the user adds "Product A"
 
    Then the cart contains 1 item

Keep backgrounds short - ideally no more than three steps.

Data Tables

Purpose: Pass structured data to steps for setup or verification.

Syntax: Attach a table to any step.

Given these users exist:
 
  | username | password | role  |
 
  | alice    | pass1    | admin |
 
  | bob      | pass2    | user  |

Step definitions parse tables into lists or maps, making bulk operations easy.

Tags

Purpose: Label and organize features or scenarios for selective execution.

Syntax: Add @tag above a Feature or Scenario.

@smoke @login 
 
Scenario: Quick login verification

Run tests by tags: cucumber --tags @smoke.

Comments

Purpose: Add notes or reminders within your feature file.

Syntax: Start lines with #. Cucumber ignores comments.

# This scenario checks for correct error message on failed login
 
Scenario: Login failure shows error
 
  Given the user is on the login page

Use comments sparingly to clarify unusual or complex logic.

Gherkin Syntax Rules and Best Practices

Follow these guidelines to keep your Gherkin syntax clear and maintainable:

  1. Indentation:
    Indent steps under Scenario or Background for readability (Cucumber ignores extra spaces).
  2. One Action per Step:
    Keep steps atomic. Don’t combine actions in one line.
# ❌ Too much at once
 
When the user enters credentials and clicks login
 
# ✅ Split steps
 
When the user enters valid credentials
 
And the user clicks the login button
  1. Business-Oriented Language:
    Describe user intent (e.g., "clicks the login button"), not technical details.
  2. Consistency:
    Use the same phrasing across scenarios to avoid duplicate step definitions.
  3. Descriptive Names:
    Give features and scenarios clear, meaningful titles.
  4. Avoid Overuse of And/But:
    If you need more than two chained And / But steps, split the scenario for clarity.

Practical Example: A Complete Feature File

# E-commerce login feature
 
@regression @login
 
Feature: Customer Login
 
  As a registered customer
 
  I want to log in so I can view and manage my orders
 
  Background:
 
    Given the login page is accessible
 
  @positive
 
  Scenario: Successful login with valid credentials
 
    Given the user has a valid account
 
    When the user enters "john.doe" and "secure123"
 
    And the user clicks the login button
 
    Then the user sees the order dashboard
 
    And the welcome message says "Hello, John!"
 
  @negative
 
  Scenario Outline: Unsuccessful login attempts
 
    Given the user is on the login page
 
    When the user enters "<username>" and "<password>"
 
    Then an error message "<error>" appears
 
    Examples:
 
      | username | password  | error                    |
 
      | john.doe | wrongpass | Invalid password         |
 
      | unknown  | secure123 | Username not found       |

This example shows how tags, a Background, and a Scenario Outline work together to cover multiple cases without extra files.

How Gherkin Works with Cucumber

When you run Cucumber:

  1. Parsing: Cucumber reads the .feature file and recognizes keywords.
  2. Step Matching: It finds step definitions based on text or regular expressions.
  3. Execution: It runs the linked code—this could mean browser actions via Selenium, API calls, or unit test checks.
  4. Reporting: It generates clear reports showing passed, failed, and skipped scenarios.

Pro Tips:

  • Keep step definitions DRY by extracting shared code.
  • Use exact text matching whenever possible—it keeps things simpler.
  • Organize step definitions by feature or component to stay organized.

For instance, the step When the user enters "john.doe" and "secure123" might map to a Java step definition like:

java  
@When("the user enters {string} and {string}")
public void enterCredentials(String username, String password) {
    loginPage.enterUsername(username);
    loginPage.enterPassword(password);
}

Conclusion

Gherkin is deceptively simple but incredibly powerful. With its keyword-driven style—Feature, Scenario, Given, When, Then—you can write clear, executable specifications that everyone understands. Use Scenario Outlines, Backgrounds, and Data Tables to keep tests DRY and flexible. Follow best practices to maintain clean, readable feature files. Mastering Gherkin helps your team stay aligned, delivers reliable tests, and ensures your software meets business needs.

Testingy offers a comprehensive test management solution that lets you organize, track, and report on your Gherkin scenarios directly within your workflow.

Related Blogs