Writing Feature Files

A Feature File in Cucumber is a file where test scenarios are written using Gherkin syntax. It has a .feature extension and follows a structured format that describes application behavior in plain English.

Structure of a Feature File

A feature file typically includes:

  1. Feature: A high-level description of the functionality being tested.
  2. Scenario: A specific test case with defined steps.
  3. Given-When-Then: The steps defining test flow.
  4. Scenario Outline: A parameterized test case for data-driven testing.

Example: Login Feature File

Feature: Login Functionality

  Scenario: Successful login
    Given the user is on the login page
    When the user enters valid credentials
    Then the user should be redirected to the homepage

  Scenario: Invalid login
    Given the user is on the login page
    When the user enters incorrect credentials
    Then an error message should be displayed

Gherkin Syntax

Gherkin uses specific keywords to define test steps in a structured way.

1. Feature

Defines the functionality being tested.

Feature: Search Functionality
  Users should be able to search for products on the website.

2. Scenario

Describes a specific test case within the feature.

Scenario: Searching for a product

3. Given (Precondition)

Sets up the initial state before performing actions.

Given the user is on the homepage

4. When (Action/Trigger)

Defines the action that changes the system state.

When the user searches for "laptop"

5. Then (Expected Outcome)

Describes the expected result.

Then search results for "laptop" should be displayed

6. And / But (Additional Conditions)

  • And adds more details to Given/When/Then.
  • But specifies negative conditions.
Given the user is logged in
And the user is on the dashboard
When the user clicks on "Logout"
Then the user should be redirected to the login page
But the session should be cleared

7. Scenario Outline (Data-Driven Testing)

Used to run the same scenario with multiple sets of data.

Scenario Outline: Login with multiple users
  Given the user is on the login page
  When the user enters "<username>" and "<password>"
  Then the login should be "<status>"

Examples:
  | username  | password  | status  |
  | user1     | pass123   | success |
  | user2     | wrongpass | failure |

8. Comments in Gherkin

Comments start with # and are ignored during execution.

# This is a comment explaining the test case

Conclusion

Gherkin syntax makes test cases easy to read, understand, and execute in an automated manner using Cucumber. By structuring tests in Given-When-Then format, Gherkin ensures clarity and reusability in behavior-driven testing (BDD). πŸš€