Background in Cucumber Framework

In Cucumber, the Background is used to define common preconditions that should run before every Scenario in a feature file.

Instead of repeating the same "Given" or "And" steps in multiple Scenarios, you write those steps once in a Background section.

Key Points

     1. Background runs before each Scenario in a Feature file
     2. There can be only one Background per feature file
     3. The Background must appear before any Scenario or Scenario Outline
     4. It can contain one or more steps
     5. It applies to both Scenario and Scenario Outline

Syntax

Background: Delete the existing customers in the application
  Given user connects to the database
  And deletes all existing customer records


Background with Scenario

Feature: Customer operations
  Background: Delete the existing customers in the application
    Given user connects to the database
    And deletes all existing customer records
  Scenario: Add a new customer
    Given user navigates to the application
    When user selects manager login
    And adds the customer with mandatory fields
    Then success message should be shown


What Happens?

Before Scenario: Add a new customer runs, Cucumber will:

Connect to the database
Delete all customer records

Background with Scenario Outline

Feature: Customer addition with multiple data
  Background: Reset the system before each login
    Given user connects to the database
    And deletes all existing customer records
  Scenario Outline: Add multiple customers
    Given user navigates to the application
    When user selects manager login
    And adds the customer with "", "", ""
    Then verify success message is displayed
    And the customer should appear in the list
    Examples:
      | username | lastname | postcode |
      | Tester   | One      | 12345    |
      | Manager  | Two      | 23456    |
      | Employee | Three    | 34567    |


What Happens?

Cucumber runs the Background once before each iteration of the Scenario Outline, so the connect and delete steps will be executed 3 times (once per row).

Output will be 

Running Scenario: Add multiple customers
Background steps executed...
User connects to database
Customer records deleted
User navigates to the application
Manager login selected
User created: Tester
Background steps executed...
User connects to database
Customer records deleted
User navigates to the application
Manager login selected
User created: Manager
...


When to Use Background

Use Background when:

     1. The same steps are repeated in every scenario
     2. You want to initialize a clean state (e.g., login, DB reset, navigation)
 

Related Tutorials