Published
- 7 min read
Mastering Gherkin: Best Practices and Examples for Effective BDD
 Mastering Gherkin: Best Practices and Examples for Effective BDD! 🚀
Introduction
In the Behavior-Driven Development (BDD), Gherkin stands as a powerful tool for expressing requirements and specifications in a human-readable format. Its syntax is simple yet expressive, making it an excellent choice for collaborating between stakeholders, developers, and testers. However, to truly harness its potential, understanding the best practices is essential. In this blog post, we’ll delve into the intricacies of Gherkin and explore examples showcasing its various options, including Given, When, Then, But, Rule, and Background.
Understanding the Basics
Before diving into best practices, let’s have a quick refresher on Gherkin’s basic structure:
@shopping
Feature: Shopping Cart Checkout
  """
  This feature describes the functionality related to the shopping cart checkout process.
  It includes scenarios for adding items to the cart, removing items, applying discounts, handling out-of-stock items,
  and navigating back to the homepage.
  """
  Background:
    Given I am logged in
    And I have navigated to the shopping cart page
  Rule: Adding items to cart
    Scenario Outline: Add items to cart
      Given I have an empty shopping cart
      When I add "<Item>" to the cart
      Then the cart should contain "<Item>"
      But the cart should not contain "<ExcludedItem>"
      Examples:
        | Item     | ExcludedItem |
        | Shoes    | Shirt        |
        | Headphones | T-shirt     |
  Rule: Removing items from cart
    Scenario: Remove item from cart
      Given I have "<Item>" in my cart
      When I remove "<Item>" from the cart
      Then the cart should be empty
  Rule: Applying discounts
    Scenario: Apply discount to cart
      Given I have "Shoes" in my cart
      And there is a promotion for "Shoes"
      When I proceed to checkout
      Then the total price should be less than the original price
  Rule: Handling out-of-stock items
    Scenario: Handle out-of-stock item
      Given there are "<Item>" available in stock
      When I add "<Item>" to the cart
      But "<Item>" is out of stock
      Then I should receive a notification
  Scenario: Return to homepage
    Given I am on the shopping cart page
    When I click on the homepage link
    Then I should be redirected to the homepage 
Keywords 🔑
Each line that isn’t a blank line has to start with a Gherkin keyword, followed by any text you like. The only exceptions are the free-form descriptions placed underneath Example/Scenario, Background, Scenario Outline and Rule lines.
The primary keywords are:
- Feature
 - Rule (as of Gherkin 6)
 - Example (or Scenario)
 - Given, When, Then, And, But for steps (or *)
 - Background
 - Scenario Outline (or Scenario Template)
 - Examples (or Scenarios)
 
There are a few secondary keywords as well:
- """ (Doc Strings)
 - | (Data Tables)
 - @ (Tags)
 
Feature Files
Feature files serve as blueprints for behavior. They encapsulate high-level functionalities and outline what the software should do. Here’s how to structure them effectively:
Feature: Shopping Cart Checkout
  As a customer
  I want to checkout items in my shopping cart
  So that I can complete my purchase
  Scenario: Add item to cart
    Given I have an empty shopping cart
    When I add "Shoes" to the cart
    Then the cart should contain "Shoes"
  Scenario: Remove item from cart
    Given I have "Shoes" in my cart
    When I remove "Shoes" from the cart
    Then the cart should be empty 
Scenarios
Scenarios represent specific examples of feature behavior. They should be clear, concise, and focused on a single aspect of functionality. Use concrete examples to illustrate the desired behavior:
Scenario: Add item to cart
  Given I have an empty shopping cart
  When I add "Shoes" to the cart
  Then the cart should contain "Shoes" 
Backgrounds
Backgrounds allow you to define steps that are common to all scenarios within a feature. They help in reducing redundancy and improving readability:
Feature: Shopping Cart Checkout
  As a customer
  I want to checkout items in my shopping cart
  So that I can complete my purchase
  Background:
    Given I am logged in
    And I have navigated to the shopping cart page
  Scenario: Add item to cart
    When I add "Shoes" to the cart
    Then the cart should contain "Shoes"
  Scenario: Remove item from cart
    Given I have "Shoes" in my cart
    When I remove "Shoes" from the cart
    Then the cart should be empty 
Given-When-Then Structure
The Given-When-Then structure provides clarity by separating preconditions, actions, and expected outcomes:
Scenario: Add item to cart
  Given I have an empty shopping cart
  When I add "Shoes" to the cart
  Then the cart should contain "Shoes" 
But Rule
The “But” keyword allows you to express exceptions or variations within a scenario:
Scenario: Add item to cart with promotion
  Given I have an empty shopping cart
  When I add "Shoes" to the cart
  But there is a promotion for "Shoes"
  Then the cart should contain "Shoes" with discounted price 
Best Practices
Clear and Concise Language
Ensure that feature files are written in clear, understandable language, avoiding technical jargon whenever possible. This promotes collaboration and understanding across different stakeholders.
Example:
Feature: User Authentication
  As a user
  I want to log in to my account
  So that I can access my profile
  Background:
    Given I am on the login page
  Scenario: Successful Login
    Given I have entered valid credentials
    When I click the login button
    Then I should be redirected to my profile page 
Single Responsibility Principle
Each scenario should focus on testing a single behavior. This ensures that scenarios remain atomic and independent of each other, facilitating easier maintenance and debugging.
Example:
Feature: Shopping Cart
  As a shopper
  I want to add items to my cart
  So that I can purchase them later
  Scenario: Add Item to Cart
    Given my cart is empty
    When I add a product to the cart
    Then the cart should contain the added product 
Use of Background
Utilize the Background section to set up the initial state for multiple scenarios within the same feature file. This reduces redundancy and improves readability.
Example:
Feature: Product Inventory
  As a store manager
  I want to manage my product inventory
  So that I can keep track of available stock
  Background:
    Given there are 10 units of "Product A" in stock
  Scenario: Update Product Quantity
    When I update the quantity of "Product A" to 15
    Then the inventory should reflect the updated quantity 
Conditional Steps with But
Use the But keyword to denote conditional steps or exceptions to the main flow. This enhances clarity and explicitly defines alternative paths.
Example:
Feature: Account Management
  As an administrator
  I want to suspend user accounts
  So that I can enforce disciplinary actions
  Scenario: Suspend User Account
    Given the user account is active
    When I suspend the user account
    Then the user should be notified
    But the user's data should remain intact 
Utilizing Rule
Rule allows grouping of related scenarios within a feature file based on a common context. This improves organization and helps in better understanding the intent behind each scenario.
Example:
Feature: Payment Processing
  As a customer
  I want to make payments securely
  So that I can complete my purchases
  Rule: Credit Card Payments
    Scenario: Successful Credit Card Payment
      Given I have items in my cart
      When I proceed to checkout with a credit card
      Then the payment should be processed successfully
    Scenario: Declined Credit Card Payment
      Given I have items in my cart
      When I proceed to checkout with an invalid credit card
      Then the payment should be declined 
Conclusion
Gherkin, with its simple yet powerful syntax, serves as a cornerstone for effective communication and collaboration in BDD. By adhering to best practices and utilizing its various options such as Given, When, Then, But, Rule, and Background, teams can streamline their development process, resulting in higher-quality software with clear, unambiguous specifications. Embrace Gherkin, master its nuances, and elevate your BDD practices to new heights.