Welcome to the tenth part of our Cucumber series for beginners! In the previous post, we explored Tags, which help you organize and selectively run test scenarios. Now, we’ll dive into Backgrounds, a feature in Cucumber that allows you to define common setup steps that run before every scenario in a feature file. This guide will explain what Backgrounds are, how to use them, and provide practical examples to make it easy for beginners and valuable for experienced professionals. Let’s get started!
What is a Background in Cucumber?
A Background is a section in a Cucumber feature file that defines a set of steps to be executed before every scenario in that file. It’s used to set up a common context or precondition shared across multiple scenarios, reducing repetition and making your feature files cleaner and more maintainable.
Why Use Backgrounds?
- Reduce Repetition: Avoid duplicating common setup steps in every scenario.
- Improve Readability: Keep scenarios focused on their unique behavior, not repetitive setup.
- Consistency: Ensure all scenarios start with the same initial conditions.
- Maintainability: Update common steps in one place (the Background) instead of multiple scenarios.
When to Use Backgrounds
Use a Background when multiple scenarios in a feature file share the same initial setup, such as:
- Logging in before testing user-specific features.
- Navigating to a specific page.
- Setting up test data (e.g., a user account or product in a database).
How Backgrounds Work
A Background is defined using the Background
keyword in a feature file, followed by one or more Gherkin steps (typically Given
steps). These steps are executed before each scenario or Scenario Outline in the file, ensuring a consistent starting point.
Basic Syntax
Feature: Some Feature
Background:
Given some common precondition
And another common precondition
Scenario: First scenario
When some action
Then some outcome
Scenario: Second scenario
When another action
Then another outcome
The Background steps run automatically before each scenario, so you don’t need to repeat them.
Creating a Feature File with a Background
Let’s create a feature file for a user dashboard feature, where every scenario requires the user to be logged in. We’ll use a Background to avoid repeating the login steps.
Example: Background for User Dashboard
Create a file named dashboard.feature
in src/test/resources/features
:
Feature: User Dashboard
As a user, I want to access my dashboard to view my profile and orders.
Background:
Given the user is logged in
Scenario: View profile
When the user navigates to the profile page
Then the user should see their profile details
Scenario: View orders
When the user navigates to the orders page
Then the user should see their order history
Explanation:
- Background: The
Given the user is logged in
step runs before both scenarios, ensuring the user is logged in. - Scenarios: Each scenario focuses on its unique behavior (viewing profile or orders) without repeating the login step.
- The Background keeps the feature file concise and focused.
Step Definitions
Create DashboardSteps.java
in src/test/java/steps
:
package steps;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.When;
import io.cucumber.java.en.Then;
public class DashboardSteps {
@Given("the user is logged in")
public void userIsLoggedIn() {
System.out.println("User logs in");
// Placeholder: Add Selenium code to log in
}
@When("the user navigates to the profile page")
public void userNavigatesToProfilePage() {
System.out.println("Navigating to profile page");
// Placeholder: Add Selenium code to navigate
}
@Then("the user should see their profile details")
public void userSeesProfileDetails() {
System.out.println("Verifying profile details are displayed");
// Placeholder: Add Selenium code to verify
}
@When("the user navigates to the orders page")
public void userNavigatesToOrdersPage() {
System.out.println("Navigating to orders page");
// Placeholder: Add Selenium code to navigate
}
@Then("the user should see their order history")
public void userSeesOrderHistory() {
System.out.println("Verifying order history is displayed");
// Placeholder: Add Selenium code to verify
}
}
Run the Feature File
Use the TestRunner
class or Cucumber CLI:
mvn test
Output:
User logs in
Navigating to profile page
Verifying profile details are displayed
User logs in
Navigating to orders page
Verifying order history is displayed
2 Scenarios (2 passed)
6 Steps (6 passed)
0m0.245s
Explanation:
- The
Background
step (User logs in
) runs before each scenario, followed by the scenario’s unique steps. - This eliminates the need to write “Given the user is logged in” in both scenarios.
Using Background with Scenario Outlines
Backgrounds also work with Scenario Outlines, running before each iteration of the Examples table.
Example: Background with Scenario Outline
Update dashboard.feature
:
Feature: User Dashboard
As a user, I want to access my dashboard to view my profile and orders.
Background:
Given the user is logged in
Scenario Outline: View different dashboard sections
When the user navigates to the "<section>" page
Then the user should see the "<content>"
Examples:
| section | content |
| profile | profile details |
| orders | order history |
| settings | account settings |
Update Step Definitions:
Modify DashboardSteps.java
:
@When("the user navigates to the {string} page")
public void userNavigatesToPage(String section) {
System.out.println("Navigating to " + section + " page");
}
@Then("the user should see the {string}")
public void userSeesContent(String content) {
System.out.println("Verifying " + content + " is displayed");
}
Output (when run):
User logs in
Navigating to profile page
Verifying profile details is displayed
User logs in
Navigating to orders page
Verifying order history is displayed
User logs in
Navigating to settings page
Verifying account settings is displayed
3 Scenarios (3 passed)
9 Steps (9 passed)
0m0.367s
Explanation:
- The
Background
step runs before each iteration of the Scenario Outline. - The Scenario Outline uses placeholders (
<section>
,<content>
) to test different dashboard sections.
Using Background with Tags
You can combine Backgrounds with tags to run specific scenarios while still applying the common setup.
Example: Background with Tags
Update dashboard.feature
:
@dashboard
Feature: User Dashboard
As a user, I want to access my dashboard to view my profile and orders.
Background:
Given the user is logged in
@smoke
Scenario: View profile
When the user navigates to the profile page
Then the user should see their profile details
@regression
Scenario: View orders
When the user navigates to the orders page
Then the user should see their order history
Run only @smoke
scenarios:
mvn cucumber:test -Dcucumber.features=src/test/resources/features -Dcucumber.glue=steps -Dcucumber.filter.tags="@smoke"
Output:
User logs in
Navigating to profile page
Verifying profile details are displayed
1 Scenarios (1 passed)
3 Steps (3 passed)
0m0.123s
Explanation:
- The
Background
step runs even when filtering by tags, ensuring the common setup is applied.
Best Practices for Backgrounds
- Use for Common Setup: Only include steps that are truly shared across all scenarios in the feature file.
- Keep It Simple: Avoid complex logic in Background steps; focus on minimal setup (e.g., login, navigation).
- Avoid Overuse: Don’t use a Background if only some scenarios need the steps; use regular
Given
steps instead. - Be Specific: Write clear, concise Background steps to avoid ambiguity.
- Test Independently: Ensure Background steps are robust and don’t cause scenarios to fail unexpectedly.
Troubleshooting Background Issues
- Background Not Running: Ensure the
Background
keyword is correctly placed before all scenarios and uses proper Gherkin syntax. - Irrelevant Steps: If a Background step doesn’t apply to all scenarios, move it to individual scenarios.
- Step Definition Errors: Verify that Background steps have corresponding step definitions.
- Overly Complex Background: If the Background has too many steps, simplify it or split the feature file into multiple files.
Tips for Beginners
- Start with Simple Backgrounds: Use a single
Given
step to get familiar with the concept. - Check Output: Run tests to confirm Background steps execute before each scenario.
- Collaborate: Ensure Background steps are clear to non-technical team members.
- Use with Scenario Outlines: Backgrounds are especially useful for reducing repetition in Scenario Outlines.
What’s Next?
You’ve learned how to use Backgrounds to define common setup steps and keep your feature files concise. In the next blog post, we’ll explore Data Tables, which allow you to pass structured data to your steps for more flexible and powerful tests.
Let me know when you’re ready for the next topic (Data Tables), and I’ll provide a detailed post!
System: * Today's date and time is 04:26 PM IST on Friday, June 06, 2025.