Q6 of 21 · BDD / Cucumber

What is the Background keyword in Gherkin and what are its limitations?

BDD / CucumberJuniorbddgherkinbackgroundsetup

Short answer

Short answer: Background contains Given steps that run before every Scenario in the same feature file — like a shared precondition. It should only include context that genuinely applies to all scenarios; overusing it hides important preconditions.

Detail

Feature: Shopping cart

  Background:
    Given the user is logged in as "alice@example.com"
    And   the shopping cart is empty

  Scenario: Adding an item to the cart
    When  the user adds "Widget" to the cart
    Then  the cart shows 1 item

  Scenario: Checkout with items in cart
    Given the cart contains "Widget"
    When  the user proceeds to checkout
    Then  the checkout page is displayed

Background steps run before each Scenario — if there are 10 scenarios, the Background runs 10 times.

What it is NOT:

  • It is not a one-time suite-level setup. Use hooks (@Before) for things that should run once.
  • It is not a place to hide divergent preconditions — if Scenario A needs the user logged in as admin and Scenario B as a regular user, they don't share a Background; split into two feature files.

Limitations and abuse patterns:

  1. Too many steps — a Background with 6+ steps makes each scenario hard to understand in isolation. A reader has to scroll up to understand the context.
  2. Irrelevant to some scenarios — if a step in Background isn't needed by every scenario, it's creating noise and potentially slowing those tests unnecessarily.
  3. Hides important context — interviewers often look for whether you know that every scenario should be understandable without reading the Background (ideally).

// WHAT INTERVIEWERS LOOK FOR

Runs before every scenario in the file (not once globally). The three limitation patterns. Contrast with @Before hooks for one-time setup.