</>

Technology

Cucumber

Difficulty

Beginner

Interview Question

What is the use of Background keyword in Cucumber?

Answer

Background Keyword in Cucumber

Purpose

Background is used to define common precondition steps that should run before every scenario in a feature file. It avoids duplicating the same Given steps in each scenario.

Syntax

Gherkin
Feature: Online Shopping

  Background:
    Given the user is on the application login page
    And the user is logged in with valid credentials

  Scenario: Add item to cart
    When the user searches for "Laptop"
    And clicks "Add to Cart"
    Then the cart count should be "1"

  Scenario: View cart
    When the user navigates to the cart page
    Then the cart page should be displayed

In the example above, both scenarios first execute the Background steps before running their own steps.

Background vs Hooks (@Before)

Background@Before Hook
Written inFeature file (Gherkin)Java step definition
Visible toBAs, PMs, non-technicalDevelopers only
Applies toCurrent feature file onlyAll scenarios (by default)
Tagged scopeNoYes (@Before("@login"))
PurposeBusiness preconditionsTechnical setup (driver init)

Real Example

Gherkin
Feature: Banking Transactions

  Background:
    Given the user is on the application login page
    When the user enters credentials "user01" and "Pass@123"
    And the user clicks Login
    Then the user should be on the home page

  Scenario: Check account balance
    When the user clicks on "My Account"
    Then the balance should be displayed

  Scenario: Transfer funds
    When the user initiates a transfer of "$500" to "ACC-456"
    Then the transfer confirmation should appear

Key Rules

  1. Only Given steps should be in Background (best practice)
  2. There can be only one Background per feature file
  3. Background runs before every scenario, including Scenario Outline rows
  4. Background does NOT run before scenarios in other feature files

Follow AutomateQA

Related Topics