Cucumber Rule Keyword

Profile picture for user devraj

The Rule is an optional keyword in Cucumber that groups a set of Scenarios or communicate agreed restrictions about the coverage of the story.

Cucumber Rule Keyword

  1. Supported in Cucumber: Rule was added in Gherkin v6 in late 2018. In Cucumber, it is an optional keyword available from the Cucumber 6 version. The purpose of the Rule keyword is to represent one business rule that should be implemented.
  2. Relation with Acceptance Criteria: A single rule is equal to one acceptance criterion. Acceptance criteria are a collection of rules which cover characteristics of a system’s behavior and from which scenarios can be derived.
  3. Group Scenarios: The Rule keyword is simply a grouping construct. It groups several scenarios that belong to the same business rule. Without its Scenarios, a Rule may be ambiguous. Without a Rule, a scenario lacks context. Together they fully specify the expected behavior of the product and guide the development team’s efforts.
  4. When to Add Rules: For each Rule, we may need one or more scenarios to explain it. A rule with many Scenarios might be over-complex. A Rule should contain one or more Scenarios that illustrate the particular Rule. 
  5. Supported by IDEs and Tools: Modern IDEs can display scenarios grouped by Rule – and automation results are grouped by Rule as well.
  6. Tagging Rules:  Since scenarios illustrate a rule, it would make sense for them to inherit any tags applied at the rule level. A scenario will inherit any Tags applied to the Rule that it illustrates and any Tags applied to the feature. 
  7. Background in Rules: For each rule, You can have a separate Background section containing the common steps inherited by Scenarios grouped which are part of Rule.

Cucumber Rule Example

Feature: Feature 1

    Given I am on the homepage
  Rule: This is Rule 1
    - Description Line 1
    - Description Line 2
    Background: 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

  Rule: This is Rule 1
    - Description Line 1
    - Description Line 2
    Background: Rule 2 background
      When I click on Ask Doubt link

    Scenario: Scenario 3
      Then I should see "Ask Doubt" Heading

In above example

  • Scenario 1 and Scenario 2 belong to Rule 1, and Scenario 3 is part of Rule 2. 
  • Rule 1 and Rule 2 are tagged and have their separate Background section.