bdd: writing better scenarios

2020-10-30

 | 

~3 min read

 | 

446 words

The thing I like about BDD is that it reminds me of product management and user stories. Features are about solving problems and adding value. When I wrote user stories in the past, I found that using a who, what, when framework for describing the problem was a good place to start.

Writing out BDD scenarios is quite similar though it’s common to struggle to write them. One reason writing scenarios is challenging is because of the close association between BDD and Gherkin, a domain specific language (DSL) created for BDD, it’s most easily recognized by its “Given, When, Then” keywords. There are at least some who find the formality of Gherkin stifling and difficult and want to “just use English” - even while staying true to the spirit of BDD.1 I’m all for that, though I would argue there’s value in a formal structured approach without too much ceremony (a balance Gherkin strikes to me). The answer then isn’t getting rid of Gherkin, which is a tool, but learning to communicate more clearly.

To that end, I found Cucumber.io’s article on Writing Better Gherkin useful. It’s interesting, though not terribly surprising, to see the similarities between writing better scenarios with Gherkin and writing better commits. The takeaway: both benefit from a declarative style.

To use a relatively basic example, we can replace the imperative style of:2

Given a user goes to '/login'
When the user enters a valid email/password combination
    And the user presses the "login" button
Then the user is redirected to '/profile'

With a more declarative scenario:

When a user logs in
Then the user will see their profile

In the former approach, each step describes a specific instruction that may change in the future (e.g., handling SSO capabilities in addition to basic authentication). The latter is not concerned with these details and focuses instead on the intended behavior of the scenario.

Writing better scenarios can make a big difference in how software is built. Learning to write better scenarios - whether it’s with Gherkin or plain English - is about focusing on the what and why and letting how be an implementation detail. As with so many of the other lessons I’ve learned over the past few years, however, it is not a technical improvement, but through better communication, that gains are made.

Footnotes

  • 1 Companies like Functionize are working to get around this formality through the use of language processing algorithms.
  • 2 The example is inspired from the Cucumber.io article which has additional examples. To demonstrate the awkwardness of Gherkin, Functionalize also provided several examples - all of which were written imperatively.


Hi there and thanks for reading! My name's Stephen. I live in Chicago with my wife, Kate, and dog, Finn. Want more? See about and get in touch!