Answer
Background Keyword Example
Basic Example
Gherkin
Feature: Banking Application
Background:
Given the user is on the application login page
Scenario: Check account balance
When the user logs in with valid credentials
And navigates to "My Account"
Then the balance "$5,000" should be displayed
Scenario: Transfer funds
When the user logs in with valid credentials
And initiates a transfer of "$200" to account "ACC-789"
Then the transaction should show "Transfer Successful"
The Background step "Given the user is on the application login page" runs before each scenario automatically.
Real-World Background Example
Gherkin
Feature: E-Commerce Product Management (Admin)
Background:
Given the admin opens the Chrome browser
And the admin navigates to the admin portal
And the admin logs in with username "admin" and password "Admin@123"
And the admin is on the Products management page
Scenario: Add new product
When the admin clicks "Add New Product"
And fills in product name "Wireless Headphones"
And sets price "89.99"
And clicks "Save Product"
Then the success message "Product added successfully" should appear
Scenario: Edit existing product price
When the admin finds product "Wireless Headphones"
And updates the price to "79.99"
And clicks "Update"
Then the price should show "79.99" in the product list
Scenario: Delete a product
When the admin finds product "Old Product"
And clicks the Delete icon
And confirms deletion
Then the product should no longer appear in the list
Execution Order
CODE
Scenario 1 runs as:
Given the admin opens Chrome ← Background
And admin navigates to portal ← Background
And admin logs in ← Background
And admin is on Products page ← Background
When admin clicks "Add New Product" ← Scenario step
...
Scenario 2 runs as:
Given the admin opens Chrome ← Background (again)
And admin navigates to portal ← Background (again)
...
Background as Precondition
Gherkin
Background:
Given the user is on the application login page
-- This is equivalent to writing this in EVERY scenario:
Scenario: Some test
Given the user is on the application login page
When ...
