What is the Background keyword in Cucumber?


The Background keyword is applied to replicate the same steps before all Scenarios within a Feature File.

Background Rules

Let us describe some of the rules while applying Background −

  • It should be used for defining simple steps unless we are forced to bring the application to a state which requires complicated steps to be carried out. As requested by the stakeholders of the project.

  • It should be brief and realistic.

  • All the Scenarios should also be short and to the point.

Background Example

Let us see an example where we have used Background steps to be executed before all the tests in the Feature File. For instance, to add a normal and admin user for an application, we require the following steps to be run before the execution of the actual tests −

  • Launch the application URL.
  • Submit the username and password.

Feature File

Feature − Member addition

Background

Given launch URL

Then enter name and password

Scenario − Normal user addition

Given user is on normal user additon screeen

When enters normal user details

Then user should be added as normal user

Scenario− Admin user addition

Given user is on admin user addition screen

When enters admin user details

Then user should be added as admin user

Example

Step Definition File

using System;
using TechTalk.SpecFlow;
namespace SpecFlowProject1.Features {
   [Binding]
   public class MemberAdditionSteps {
      [Given(@"launch URL")]
      public void GivenLaunchURL() {
         Console.WriteLine("Url launched");
      }
      [Given(@"user is on normal user additon screeen")]
      public void GivenUserIsOnNormalUserAdditonScreeen() {
         Console.WriteLine("User is on normal user addition screen");
      }
      [Given(@"user is on admin user addition screen")]
      public void GivenUserIsOnAdminUserAdditionScreen() {
         Console.WriteLine("User is on admin user addition screen");
      }
      [When(@"enters normal user details")]
      public void WhenEntersNormalUserDetails() {
         Console.WriteLine("User enters normal user details");
      }
      [When(@"enters admin user details")]
      public void WhenEntersAdminUserDetails() {
         Console.WriteLine("User enters admin user details");
      }
      [Then(@"enter name and password")]
      public void ThenEnterNameAndPassword() {
         Console.WriteLine("User enters name and password");
      }
      [Then(@"user should be added as normal user")]
      public void ThenUserShouldBeAddedAsNormalUser() {
         Console.WriteLine("User should be added as normal user");
      }
      [Then(@"user should be added as admin user")]
      public void ThenUserShouldBeAddedAsAdminUser() {
         Console.WriteLine("User should be added as admin user");
      }
   }
}

Output

Updated on: 18-Nov-2021

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements