A Gherkin styleguide

Few, if any websites make useful recommendations about how to phrase Gherkin steps, so allow me to make some suggestions in the hope they will make life simpler.

Given steps establish state

Given steps describe a current, present, extant state of the test environment (I use the term loosely) before some (to be tested) action is performed.

The fact that your Given step definition likely creates that state in code behind the scenes is irrelevant.

  • Given steps must be in past or present tense
  • Given steps must not be in the future tense
  • Given steps must not contain action. That's the job of When.

Bad:

Given I populate the database
Given I have logged in as a user
Given the welcome banner has been displayed

Good:

Given the database is populated
Given I am logged in as a user
Given the welcome banner is displayed

In the latter of each of the two examples "Given the welcome banner has been displayed" is ambiguous - is it still being displayed, or was it simply displayed at some point in the past? Use the second example "Given the welcome banner is displayed", because it's unambiguous.

When steps perform an action

  • When steps should not discuss state. That's the job of Given and Then.
  • When steps should be in present tense
When I make a transaction of £100
When I flush the db connection
When I load https://google.com/

Then steps make assertions about state

Then steps do not talk about what will, should or may be, but what is (or is not). It's hard to make meaningful assertions about human intention ("will"), let alone software written by humans.

  • Then steps must be in present tense
  • Then steps must make an assertion

Bad:

Then I will be emailed a receipt
Then I will see the user login page
Then the search input field will be displayed

Good:

Then my inbox contains an email receipt
Then the user login page is displayed
Then the search input field is displayed

Your inbox either contains the expected email receipt or it does not. Yes/No, True/False. It's easy to test or make assertions about.

Last but not least, only Then step definitions may contain code assertions. You might think that's obvious and uncontroversial, but I've seen Given and When step definitions containing them.

In summary

Given steps establish state;

When steps perform an action;

Then steps make assertions about state.

Here's a minimal but complete example:

Given I am logged in as a user
When I load https://google.com/
Then the search input field is displayed

Eliminate abiguity. Favour simplicity. Never use more words if it can be adequately expressed with fewer.