opencodez

Complete Step by Step Guide of Gherkin for Beginners

Gherkin is a plain English text language, used by BDD (Behavior Driven Development) tool xCucumberx to define and execute the test scripts.

1. What is BDD?

BDD (Behavior Driven Development) is a software development process based on an Agile method. BDD is an extension of TDD (Test-Driven Development). Instead of focusing on software development in the direction of testing, BDD focuses on software development in the direction of behavior.

Based on the requirement, the test scenarios will be written first in the natural language and easy to understand before implementing the source code to pass through all the stories. These test scripts are written as feature files and require collaboration from all project members or stakeholders.

2. Difference Between TDD and BDD?

TDD

x

(Test Driven Development)

BDD

x

(Behavior Driven Development)

Give the developer an understanding of what the system should do Focus on the behavior aspect than the implementation aspect of the system
Mostly written by the developer Written by stakeholders or non-technical person
Written unit tests Normally for acceptance testing
Low-level scenario High-level scenario
Input: specification, Output: test Input: specification, Output: implementation

3. Why we have to use BDD

  1. Help identify the right customer requirements: documents are written in natural language, any object can understand. By reading this document, customers can easily identify programmers who understand their requirements and responsibilities.
  2. It is a live document of the project: this document is always updated when there is any change so all members will not miss information when developing the system.
  3. Improve the quality of software, create useful products: because of developing software in the direction of behavior, it is possible to focus on creating products that meet the requirements of customers but still useful for users.

4. Who will write BDD?

As mentioned above, BDD will be written by project members and stakeholders. Therefore, all these people will build a BDD file to give a most general, accurate view of the project requirements.

5. How to write BDD?

BDD is written in plain text language called Gherkin.

(*) Rules for writing :

6. What is Gherkin Language?

Gherkin is the format for cucumber specifications. This is a domain-specific language that helps you describe business behavior without going into implementation details. This document acts as the documentation and framework of your automated tests.

7. Why Gherkin?

8. How to use it? Syntax? Terms?

Like Python and YAML, Gherkin is a line-oriented language used to define structure logic. Like Ruby, the tab character should be replaced with space characters, the comment line will have the # character at the beginning of the line.

Start a file will be “Feature”, then “scenarios” and steps. When running the source file xfeaturex each step will match with a predefined Ruby code block called xStep Definitionsx. In this scenario, a comment can be added anywhere you want, but it should begin with the # sign. It reads each line after removing Ghrekinxs keywords like given, when, then, etc.

Gherkin syntax?

Given, When, Then. Also, some more complex cases have And, But …

Given: Preconditions, use to describe the original context. Introduce into the system a state to start interacting with the system. Givenxs goal is to put the system into a known state before use (or the external system) to start interacting with the system (in the When step).

If you have worked with a use case, Givens is a prerequisite.

When: describe the main action events the user performed. The use of the keyword “then” is to see the result after the action in the when “step”. However, you can only verify notable changes.

Then: Expected output. “Then” was used to observe the result. Observations must be related to business values / benefits in “Feature” description. Observations must check the output of the system (a report, user interface, messages, etc.)

9. Gherkin terms

Feature: Title of the Scenario

All conventional x* .featurex files include only one feature.

The line begins with the keyword xFeature:x.

A Feature usually consists of a list of Scenarios. Can write whatever you want until the beginning of the first Scenario (when the new line begins with the word xScenario:x)

Tags can be used to group features and scenarios together, regardless of the file and directory structure. Each scenario consists of a list of steps, steps starting with keywords such as (Given, When, Then, But or And). Additionally, the feature may include a scenario outline and background

Scenario:

Each feature file may have multiple scenarios, and each scenario starts with a script.

Background:

The “Background” keyword helps you add some context to the script. It may contain several script steps, but the only difference is that it should be run before each script.

Given:

Use this keyword to bring the system to a familiar state before the user starts interacting with the system. However, you can skip writing user interactions in the given steps if given in the xPreconditionx step.

When:

The purpose of “When” is to describe events, the main action that a user uses.

Then:

The use of the keyword xthenx is to see the result after the action in the “When” step. However, you can only verify notable changes.

And, But:

Used when there are many “Given”, “When”, “Then”

10. Gherkin Explained With Example:

Before moving forward we should know what is cucumber?

Cucumber is a tool that supports BDD. Gherkin is a set of grammar rules that makes plain text structured enough for Cucumber to understand.

Let go to an example below:

Feature: Addition

Scenario: Add two number

Given the numbers 1 and 2

When they are added together

Then should the result be 3

What to do first?

1. Install Node.js:

$ sudo apt-get install nodejs

2. Create “myGherkin” directory:

$ mkdir myGherkin

3. Install cucumber:

$ npm install cucumber --save-dev

4. Open package.json and edit content as below:

{
  "name": "myGherkin",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "cucumber-js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "cucumber": "*"
  }
}

5. Create “features” directory: mkdir features

6. Let’s run cucumber:

/node_modules/.bin/cucumber-js

You should see something like the following (mean cucumber did not find anything to run)

0 Scenarios
0 steps
0m00.000s

7. Create a new file: “new_feature.feature” in /features, content as below:

Feature: Addition
Scenario: Add two number
Given the numbers 1 and 2
When they are added together 
Then should the result be 3

8. Run cucumber again:

You will see results like this:

UUU

Warnings:

1) Scenario: Add two number # features/new_feature.feature:2
   ? Given the numbers 1 and 2
       Undefined. Implement with the following snippet:

         Given('the numbers {int} and {int}', function (int, int2) {
         // Given('the numbers {int} and {float}', function (int, float) {
         // Given('the numbers {float} and {int}', function (float, int) {
         // Given('the numbers {float} and {float}', function (float, float2) {
           // Write code here that turns the phrase above into concrete actions
           return 'pending';
         });

   ? When they are added together
       Undefined. Implement with the following snippet:

         When('they are added together', function () {
           // Write code here that turns the phrase above into concrete actions
           return 'pending';
         });

UUU means that there are three undefined steps. I also got three snippet suggestions.

9. Create a new file: features/step_definitions/addition_steps.js

const { Before, Given, When, Then } = require('cucumber')

Given('the numbers {int} and {int}', function (int, int2) {
    // Write code here that turns the phrase above into concrete actions
    return 'pending'
});


 When('they are added together', function () {
    // Write code here that turns the phrase above into concrete actions
    return 'pending'
});

Then('should the result be {int}', function (int) {
    // Write code here that turns the phrase above into concrete actions
    return 'pending'
});

10. Run cucumber again: ./node_modules/.bin/cucumber-js

You should see the results as below:

P--

Warnings:

1) Scenario: Add two number # features/new_feature.feature:2
   ? Given the numbers 1 and 2 # features/step_definitions/addition_steps.js:3
       Pending
   - When they are added together # features/step_definitions/addition_steps.js:9
   - Then should the result be 3 # features/step_definitions/addition_steps.js:14

1 scenario (1 pending)
3 steps (1 pending, 2 skipped)
0m00.001s

11. Create a new files: myGherkin/lib/additional.js with below content:

class Calculator {

    constructor(x, y) {
        this.x = x;
        this.y = y;
    }

    add() {
        this.result = this.x + this.y;
    }

    getResult() {
        return this.result;
    }
}

module.exports = Calculator;

12. Update “addition_steps.js” with below content:

const assert = require('assert')
const {Before, Given, When, Then} = require('cucumber');
const Calculator = require('../../lib/additional');

let calculator;

Given('the numbers {int} and {int}', function (x, y) {
    calculator = new Calculator(x, y);
});

When('they are added together', function () {
    calculator.add();
});

Then('should the result be {int}', function (expected) {
    assert.equal(calculator.getResult(), expected)
});

13. Run cucumber again, you will see results as below:

1 scenario (1 passed)
3 steps (3 passed)
0m00.000s

12. Pros / Cons of Gherkin

  1. Help determine the right customer requirements: because the document is based on natural language direction, any object can understand, so when reading this document, customers can easily know if the programmer is going in the right direction they want it.
  2. The code writing style is easy to maintain and implement
  3. An effective tool for testing
  1. It requires a high degree of business engagement and cooperation
  2. May not work well in all scenarios
  3. Poorly written tests can easily increase test maintenance costs

13. How to use BDD + Selenium

1. Install sudo apt-get install nodejs

2. Use below commands to check step 1 is successful:

$ npm -v
$ node -v

3. Install selenium webdriver:

$ npm install selenium-webdriver

4. Install chrome driver:

$ npm install -g chromedriver

5. Use “addition_steps.js” file above and modify the content:

const assert = require('assert');
const webdriver = require('selenium-webdriver');
const browser = new webdriver.Builder()
  .usingServer()
  .withCapabilities({'browserName': 'firefox' })
  .build();

browser.get('http://en.wikipedia.org/wiki/Wiki');

6. Don’t forget to update content for “new_feature.feature” file:

Feature: Access Wiki
Scenario: Wiki can be opened in Firefox
Given I have opened a Web Browser
When I load the Wikipedia article on "Wiki" 
Then Wiki page is displayed

7. Go to terminal and run cucumber:

$ ./node_modules/.bin/cucumber-js

=x Wiki page is displayed on Firefox browser.

Conclusion:

Gherkin is the format for cucumber specifications. It is a stream-oriented language like YAML and Python. Gherkin instruction connects the concept of human causes and results in the concepts of software inputs/processes and outputs.

In Gherkin cucumber, each script should perform separately. The greatest advantage of Gherkin is that it is simple enough for non-programmers to understand

You May Also Interested In:

151+ Most Important Selenium Interview Questions

Front-end / UI Automation Testing with Cypress

API Testing with Java Using Rest Assured – Sample Code Provided

x