Beginner Chapter 4 · 12 min read

Writing Step Definitions

Map Gherkin steps to code — create step definition methods, use Cucumber expressions, capture parameters, and handle step matching.

Step Definitions — Connecting Gherkin to Code

Step definitions are the glue between human-readable Gherkin and executable code. Each Given, When, or Then line matches a method via pattern matching.

Cucumber Expressions vs Regex

Cucumber 7+ supports Cucumber Expressions — simpler, more readable alternatives to regex. Use {string} for quoted strings, {int} for numbers, {word} for single words. You can still use full regex when needed.

Best Practices

  • Keep step definitions thin — delegate to page objects or helpers
  • Reuse steps across scenarios — write generic, parameterized steps
  • Avoid coupling steps to a single scenario
LoginSteps.java
package com.bdd.course.stepdefinitions;

import io.cucumber.java.en.Given;
import io.cucumber.java.en.When;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.And;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;

public class LoginSteps {

    private WebDriver driver;
    private String currentPage;

    // Cucumber Expression — captures {string}
    @Given("the user is on the login page")
    public void theUserIsOnTheLoginPage() {
        driver = new ChromeDriver();
        driver.get("https://example.com/login");
        currentPage = "login";
    }

    // Captures two string parameters
    @When("the user enters username {string} and password {string}")
    public void theUserEntersCredentials(String username, String password) {
        // delegate to page object
        System.out.println("Entering: " + username + " / " + password);
    }

    @And("the user clicks the login button")
    public void theUserClicksLogin() {
        System.out.println("Clicking login...");
    }

    @Then("the user should be redirected to the dashboard")
    public void theUserShouldBeOnDashboard() {
        currentPage = "dashboard";
        Assert.assertEquals(currentPage, "dashboard");
    }

    // {string} captures the quoted value from Gherkin
    @Then("the welcome message should display {string}")
    public void welcomeMessageShouldDisplay(String expectedMessage) {
        System.out.println("Verifying: " + expectedMessage);
    }

    @Then("an error message {string} should be displayed")
    public void errorMessageShouldBeDisplayed(String expectedError) {
        System.out.println("Error expected: " + expectedError);
    }
}
SearchSteps.java
package com.bdd.course.stepdefinitions;

import io.cucumber.java.en.*;

public class SearchSteps {

    // Regex-style step definition (also supported)
    @When("^the user searches for "([^"]*)"$")
    public void theUserSearchesFor(String query) {
        System.out.println("Searching for: " + query);
    }

    @Then("search results should be displayed")
    public void searchResultsShouldBeDisplayed() {
        // Verify results are visible
    }

    // {int} captures an integer parameter
    @Then("the results count should be {int}")
    public void resultsCountShouldBe(int expectedCount) {
        System.out.println("Expected count: " + expectedCount);
    }

    @Then("the results count should be greater than {int}")
    public void resultsCountGreaterThan(int minCount) {
        System.out.println("Min count: " + minCount);
    }

    @Then("the results should not contain {string}")
    public void resultsShouldNotContain(String unwanted) {
        System.out.println("Should not contain: " + unwanted);
    }

    @Then("the {string} message should be displayed")
    public void messageShouldBeDisplayed(String message) {
        System.out.println("Message: " + message);
    }

    @Then("all products should be displayed")
    public void allProductsShouldBeDisplayed() {
        // Verify all products shown
    }
}
login_steps.py
# features/steps/login_steps.py
from behave import given, when, then
from selenium import webdriver

@given('the user is on the login page')
def step_user_on_login_page(context):
    context.driver = webdriver.Chrome()
    context.driver.get("https://example.com/login")
    context.current_page = "login"

@when('the user enters username "{username}" and password "{password}"')
def step_user_enters_credentials(context, username, password):
    # Delegate to page object
    print(f"Entering: {username} / {password}")

@when('the user clicks the login button')
def step_user_clicks_login(context):
    print("Clicking login...")

@then('the user should be redirected to the dashboard')
def step_user_on_dashboard(context):
    context.current_page = "dashboard"
    assert context.current_page == "dashboard"

@then('the welcome message should display "{expected_message}"')
def step_welcome_message(context, expected_message):
    print(f"Verifying: {expected_message}")

@then('an error message "{expected_error}" should be displayed')
def step_error_message(context, expected_error):
    print(f"Error expected: {expected_error}")
search_steps.py
# features/steps/search_steps.py
from behave import given, when, then
import re

@when('the user searches for "{query}"')
def step_user_searches(context, query):
    print(f"Searching for: {query}")

@then('search results should be displayed')
def step_results_displayed(context):
    pass  # Verify results visible

@then('the results count should be {count:d}')
def step_results_count(context, count):
    print(f"Expected count: {count}")

@then('the results count should be greater than {min_count:d}')
def step_results_greater_than(context, min_count):
    print(f"Min count: {min_count}")

@then('the results should not contain "{unwanted}"')
def step_results_not_contain(context, unwanted):
    print(f"Should not contain: {unwanted}")

@then('the "{message}" message should be displayed')
def step_message_displayed(context, message):
    print(f"Message: {message}")

@then('all products should be displayed')
def step_all_products(context):
    pass

Cucumber BDD Beginner Writing Step Definitions

Written by PV

© 2026 All Rights Reserved