As you may have noticed in the example above, we are rewriting the same step multiple times:
Given the user is on the login page
This can be exceptionally tedious, especially if we have more than one given step that is reused. Gherkin provides a solution for this by giving us another keyword to work with: Background:.
The background keyword serves to run the steps declared underneath it before every scenario in the Feature. Be sure not to add background step unless you are positive it is necessary for every scenario. Like the other keywords, Background is followed by a description or name and can have comments listed below it. Much like Feature and Scenario, Background must be proceeded by a colon.
Feature: Product Login
As a user, I would like to be able to use my credentials to successfully
login.
Rules:
- The user must have a valid username
- The user must have a valid password
- The user must have an active subscription
- User is locked out after 3 invalid attempts
- User will get a generic error message following
login attempt with invalid credentials
Background: The user starts out on the login page
Given the user is on the login page
Scenario: The user successfully logs in with valid credentials
This scenario tests that a user is able to successfully login
provided they enter a valid username, valid password, and
currently have an active subscription on their account.
When the user signs in with "valid" credentials
Then the user should be logged in
Scenario: The user attempts to log in with invalid credentials
This scenario tests that a user is not able to log in when
they enter invalid credentials
When the user signs in with "invalid" credentials
Then the user should be logged in
Scenario: The user is locked out after too many failed attempts
This scenario validates that the user is locked out
of their account after failing three consecutive
attempts to log in
When the user fails to log in 3 times
Then the user should be locked out of their account