October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk6 min

How to Use Gherkin and Selenium for Behavior-Driven Development

A practical guide to collaborative BDD examples, readable Gherkin scenarios, Cucumber step definitions, and Selenium browser checks.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use Gherkin to describe a behavior in language the team can agree on, Cucumber to match and run those steps, and Selenium WebDriver when the behavior needs a real browser. The order matters: agree on the example first, then automate it. BDD is the collaborative process; Gherkin, Cucumber, and Selenium each have distinct roles within it.

What each part does

  • BDD is a way for product, development, and QA to discover and refine examples together, creating shared understanding of what the software should do. Automation is one practice within BDD, not the whole method.
  • Gherkin is the structured language used to write those examples in .feature files.
  • Cucumber reads the feature file, matches each step to a step definition, runs the definitions in sequence, and reports the result.
  • Selenium WebDriver drives a browser: it can open a page, locate elements, interact with them, and wait for a rendered result. Cucumber is not itself a browser automation tool.

Keep the scenario focused on the behavior people care about. Keep browser mechanics—selectors, clicks, waits, and driver lifecycle—in the step-definition and test-support code.

Agree on an example before automating it

Choose one small behavior the team can describe and verify. Ask what must already be true, what the user does, and what observable result should follow. This discovery conversation is the BDD work; writing a feature file without it can merely turn a UI script into a different syntax.

For instance, a team building a search page might agree that a visitor can search for a term and see matching results. The example should express that outcome, not prescribe which field to click or which CSS selector to use.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Write the behavior in Gherkin

A feature file groups related examples. Given establishes context, When describes an event or action, and Then states an expected result. And and But can make a sequence easier to read.

Feature: Search

  Scenario: A visitor finds matching content
    Given I am on the search page
    When I search for "Cheese!"
    Then the page title starts with "cheese"

This is an illustrative scenario based on Cucumber’s browser-guide example. For a production test, prefer a stable application and data your team controls; an external search site can change independently of your product.

Choose the right Gherkin structure

  • Use a Rule when several examples illustrate one business rule.
  • Use a Scenario Outline with an Examples table when a small set of data variations exercises the same behavior.
  • Use a Data Table for structured step input, or a Doc String for a larger text input.
  • Keep an example concise. Cucumber’s Gherkin reference offers 3–5 steps as a guideline, not a hard limit.

Avoid making each click a step. “When I click the blue button and type into the third field” ties the shared example to layout. Describe the user’s intent instead, and implement the interaction in code. Also, keywords do not distinguish otherwise identical step text during matching: avoid duplicate step definitions and make the wording unambiguous.

Connect Gherkin steps to Selenium with Cucumber

Below is a Java illustration for a team-owned search page. It assumes the page exposes an input with data-testid="search-input", a submit control with data-testid="search-submit", and a results heading with data-testid="search-results". Those selectors are example application conventions, not requirements imposed by Cucumber or Selenium. Adapt them to your app and your Cucumber Java project’s dependency and runner setup.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Feature file

Feature: Search

  Scenario: A visitor sees results for a search
    Given I am on the search page
    When I search for "Cheese!"
    Then the results heading contains "Cheese!"

Java step definitions and scenario-scoped browser

package example;

import io.cucumber.java.After;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.time.Duration;

import static org.junit.jupiter.api.Assertions.assertTrue;

public class SearchSteps {
    private WebDriver driver;
    private WebDriverWait wait;

    @Given("I am on the search page")
    public void iAmOnTheSearchPage() {
        driver = new ChromeDriver();
        wait = new WebDriverWait(driver, Duration.ofSeconds(10));
        String baseUrl = System.getProperty("app.url", "http://localhost:8080");
        driver.get(baseUrl + "/search");
    }

    @When("I search for {string}")
    public void iSearchFor(String term) {
        wait.until(ExpectedConditions.visibilityOfElementLocated(
                By.cssSelector("[data-testid='search-input']")))
            .sendKeys(term);
        driver.findElement(By.cssSelector("[data-testid='search-submit']")).click();
    }

    @Then("the results heading contains {string}")
    public void theResultsHeadingContains(String expected) {
        String heading = wait.until(ExpectedConditions.visibilityOfElementLocated(
                By.cssSelector("[data-testid='search-results']")))
            .getText();
        assertTrue(heading.contains(expected),
                "Expected results heading to contain '" + expected + "' but was '" + heading + "'");
    }

    @After
    public void closeBrowser() {
        if (driver != null) {
            driver.quit();
        }
    }
}

The code shows the responsibilities: Cucumber binds readable step text to Java methods; those methods use WebDriver to interact with the app; the Then checks a visible result. The exact fixture, runner, and dependency configuration depends on the project’s Cucumber implementation and build setup.

Wait for the result and manage browser state

Dynamic pages may not be ready as soon as a navigation or click returns. Prefer an explicit wait for the condition that represents the expected state—such as a visible result heading—rather than sleeping for an arbitrary duration. An explicit wait can fail with a useful timeout if the condition never becomes true.

  • Create the driver in scenario-scoped support or a fixture, and make it available to that scenario’s step definitions.
  • Close the driver in teardown even if an assertion fails. The @After hook above checks for an initialized driver before quitting it.
  • When running scenarios in parallel, isolate each scenario’s driver and test data by scenario or worker. Do not share mutable browser state across scenarios.
  • Use a stable test environment and owned data where possible, so changes to unrelated external pages do not appear as product regressions.

Run and debug one feature at a time

  1. Start the application and browser environment your test expects.
  2. Run the single feature or scenario with your project’s Cucumber runner.
  3. Check that every step matches exactly one step definition. An undefined step needs an implementation; an ambiguous match needs clearer wording or a corrected definition.
  4. When a scenario fails, identify whether the failure came from browser startup/navigation, a missing or late element, or the result assertion. Read the exception and the scenario’s expected state before changing the wait.
  5. Where your binding and reporter support it, attach a screenshot or other browser diagnostic on failure.

Cucumber reports results by scenario. A passing scenario means the exercised path met its assertion in that run; it does not establish that every browser, data state, or application path works.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Keep browser scenarios at the right test level

Use Selenium when browser behavior is part of what you need to validate: for example, that a visitor can submit a search and see a result in the interface. If the behavior is internal to a component and can be shown more directly with a lower-level test, that may give clearer feedback. BDD examples can guide implementation while unit or component tests cover lower-level details; not every test needs Gherkin or a browser.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Or skip the browser setup

If your goal is to capture a page image or PDF rather than exercise an interactive acceptance path, ScreenshotNeo is a website screenshot API and MCP server—not a replacement for Selenium assertions. A single GET request can return an image or PDF. See the ScreenshotNeo API documentation.

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

ScreenshotNeo accepts cookie and consent banners like a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each step can be turned off. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers report the page verdict and billing status. Its MCP server offers take_screenshot, get_page_info, and capture_pdf for AI agents. The free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 shots.

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

Where to learn more

Cucumber’s learning materials include free Cucumber School videos and recommendations for BDD books, including The Cucumber Book, BDD in Action, and The Cucumber Field Guide. For Java readers specifically, the publisher listing for The Cucumber for Java Book describes coverage of Selenium-driven applications and asynchronous Ajax calls; check the listing for current edition and availability.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Frequently Asked Questions

Can Gherkin scenarios run without Selenium?

Yes. Gherkin describes examples and Cucumber executes their step definitions; those definitions can exercise a non-browser interface or lower-level test instead of WebDriver.

Which Cucumber language should a team choose?

Choose a binding supported by the project’s language and the team’s ability to maintain it. Cucumber’s browser guide includes Java, Kotlin, JavaScript, and Ruby examples.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.