When To Use Given Or When In Cucumber
Gherkin
05/01/2023
It can be difficult to know whether a step should be defined as a Given
or When
step. However, a general rule of advice is to keep the scenarios as brief as possible. The goal is to be descriptive, not exhaustive. As a consequence, it's recommended to restrict yourself to a single When
statement in a scenario.
Here's a common example:
Given the user is unauthenticatedWhen the user provides incorrect credentialsAnd the user clicks on "Login"Then the user is prevented from logging in
One can reasonably argue that entering a false username and password as well as submitting the credentials constitute actions of this scenario. However, if a scenario should only contain a single When
step, this step should be responsible for the outcome. Taking this into consideration, one would rewrite the previous scenario as follows.
Given the user is unauthenticatedAnd the user clicks on "Login"When the user provides incorrect credentialsThen the user is prevented from logging in
The act of a user submitting their credentials should be part of the context, while entering false credentials should be the single When
statement. That is because it is responsible for the outcome, i.e. being refused login.