Cucumber ordering of Given, When, Then (Given, When, Then, When, Then)

Charlie Seligman picture Charlie Seligman · Jul 12, 2017 · Viewed 16.1k times · Source

As an End-to-end Automation Tester I have always assumed that Given, When, Then statements (incorporated in the Gherkin Language when using Cucumber) should only ever appear in the order of 1. Given, 2. When, 3. Then.

i.e. A test should not follow, for example, Given, When, Then, When, Then. And instead should follow Given, When, Then only.

The reason for this assumption was along the lines of a single test only testing one area of the application.

However, I noticed on some gherkin examples on the web, that they use the following ordering sometimes: Given, When, Then, When, Then.

Does anyone know if this moving back to Whens after writing a Then is acceptable best practice? I appreciate the test will still work, just wondering if this is good or bad practice.

Answer

Todd A. Jacobs picture Todd A. Jacobs · Jul 15, 2017

Syntactically Interchangeable; Linguistically Different

The Gherkin syntax currently includes six keywords for describing feature steps:

  1. Given
  2. When
  3. Then
  4. And
  5. But
  6. *

The keywords are there for human consumption and the ease of conveying business logic. However, the Gherkin language itself treats the keywords as interchangeable symbols, so you could just as grammatically (from a Gherkin point of view) write tortured English like:

But for a dollar held
Then another dollar more
Given ownership of two dollars am I.

This is perfectly valid Gherkin, but a terrible representation of counting money. So, if all the words are interchangeable, why have so many of them? The wiki is quite clear that they provide a set of conventions to facilitate communication in a more natural style, and the wiki even gives a few examples of how the words are meant to be differentiated. The wiki also specifically says:

Cucumber doesn’t technically distinguish between these...[kinds] of steps. However, we strongly recommend that you do! These words have been carefully selected for their purpose, and you should know what the purpose is to get into the BDD mindset.

In other words, use the Gherkin terms to communicate in (relatively) natural language about your feature, and bury the arcana in step definitions. Use whatever keyword fits most naturally in the linguistic flow, and don't sweat a well-written scenario that doesn't rigidly adhere to a convention that may not apply in all cases.