Having used Gherkin in a couple of different testing projects, I thought I’d provide a Quick Intro to Gherkin, for those not familiar with it. So far, I’ve used Gherkin as a way of documenting tests, rather than automating tests, but it’s used in both scenarios.
Gherkin Overview
• Gherkin provides a scripted way of describing how your software works, without detailing how it is implemented.
• In Gherkin, the requirements for a particular feature are grouped into a single text file, called a feature file.
• A feature file contains a short description of the feature, followed by one or more scenarios.
• Gherkin is the language used in Cucumber, a tool for running automated tests.
Gherkin Syntax and Keywords
• Most lines in Gherkin start with a keyword.
• Comment lines begin with a # sign.
• The Gherkin Keywords are – Given, When, Then, And, But
• The order of a scenario is Given… When… Then…
o Given – describes the pre-conditions for the scenario and the state.
o When – describes the action under test.
o Then – describes the expected outcomes / results.
• The And and But keywords can be used to join several Given, When or Then steps together in a more readable way
Some generic Gherkin Examples
Feature: Moving money between accounts
In order to manage my money more efficiently As a bank client I want to transfer funds between my accounts whenever I need to
Scenario: Transferring money to a savings account Given my current account has a balance of 1000.00 And my savings account has a balance of 2000.00 When I transfer 500.00 from my current account to my savings account Then I should have 500.00 in my current account And I should have 2500.00 in my savings account
Scenario Outline
There is also a special case where several related scenarios can be grouped into a single scenario, using a table of examples – this is known as a scenario outline.
Scenario Outline: Earning interest Given I have an account of with a balance of When the monthly interest is calculated Then I should have earned at an annual interest rate of And I should have a new balance of Examples: | initial-balance | account-type | interest-rate | new-balance | 10000 | current | 1 | 10008.33 | 10000 | savings | 3 | 10025 | 10000 | supersaver | 5 | 10041.67
More Info
• More info on Cucumber and Given When Then
• Writing Features and Gherkin Syntax
Recommended books