Background in Cucumber Rule

Profile picture for user devraj

Since Rule section groups several scenarios that belong to the same business rule. Often you find that several Scenarios with the same Rule start with a common context or steps. So for common steps, you can use the Background in rule section as well.

The background section will be executed before each Scenario or Scenario Outline in the Rule section. 

Example: Background Section in Rule

@Feature1
Feature: Feature 1

  Background:
    Given I am on the homepage
  	
  @Rule1
  Rule: This is Rule 1

    Background:
      When I click on login link
 
    Scenario: Scenario 1
      Then I should see "Registration" link

    Scenario: Scenario 2
      Then I should see "Forgot Password" link

Output

@Feature1 @Rule1
Scenario: Scenario 1                    # features/first.feature:13
  Given I am on the homepage            # com.pb.cucumbertest.stepdefinitions.FirstSD.homepage1()
  When I click on login link            # com.pb.cucumbertest.stepdefinitions.FirstSD.i_click_on_login_link()
  Then I should see "Registration" link # com.pb.cucumbertest.util.CommonSD.i_should_see_link(java.lang.String)

@Feature1 @Rule1
Scenario: Scenario 2                       # features/first.feature:16
  Given I am on the homepage               # com.pb.cucumbertest.stepdefinitions.FirstSD.homepage1()
  When I click on login link               # com.pb.cucumbertest.stepdefinitions.FirstSD.i_click_on_login_link()
  Then I should see "Forgot Password" link # com.pb.cucumbertest.util.CommonSD.i_should_see_link(java.lang.String)

In above output you can see "Given I am on the homepage" inherited from Feature level background and "When I click on login link" inherited from Rule Background section.