Background

In the previous chapter we have learned how to use scenario outline to test a scenario using multiple data. This is an important step to reusability. But still we have not completely achieved reusability. In this chapter we will learn about Background.


The Background in Specflow is like a setup section that helps avoid repetition by defining steps common to multiple scenarios.


Background is used in specflowbecause

  • To define a set of steps that are common to multiple scenarios within a feature file.
  • Instead of repeating the same initial steps in every scenario, you can put those steps in the Background. These steps will be executed before each scenario in the feature file.
  • It sets the stage for the scenarios by providing a common set of preconditions or initial actions.

Let's update the feature file used in previous chapter and update it to include Background. The updated feature file will look as the following.


Gherkin
Copy
Feature: Login functionality
  Background:
    Given the user is on the login page

  Scenario: Successful login
    When the user enters username "root" and password "admin"
    Then the user should be logged in successfully

  Scenario: Invalid login attempts
    When the user enters username "root" and password "pass"
    Then the login should fail with an error message

In the above feature file we have moved step with When keyword to Background as they were the common step in both scenario.


The steps defined in the Background section are executed before each scenario in the feature file. In your step definition file, you'd handle these steps similarly to regular steps, ensuring they are executed properly before scenario-specific steps. In our example, we do not have to make any changes to our step definition file.


So our step definition file will look as follows


C#
Copy
using TechTalk.SpecFlow;
using Xunit;

[Binding]
public class LoginSteps
{

	[Given("the user is on the login page")]
	public void navigateToLoginPage() {
		// Code to navigate to the login page
		Console.WriteLine("User is on the login page");
	}

	[Then("the user should be logged in successfully")]
	public void verifySuccessfulLogin() {
		// Code to verify successful login
		Console.WriteLine("User is logged in successfully");
	}

	[Then("the login should fail with an error message")]
	public void verifyLoginFailure() {
		// Code to verify login failure with an error message
		Console.WriteLine("Login failed with an error message");
	}

	[When("the user enters username {string} and password {string}")]
	public void theUserEntersUsernameRootAndPasswordAdmin(string username, string password)
	{
		Console.WriteLine("The user enters username " + username + " and password " + password + ".");
	}
}

The Background helps maintain clarity and avoids redundancy by setting up a consistent starting point for scenarios that share common initial conditions or actions.