Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Cucumber Cookbook
Cucumber Cookbook

Cucumber Cookbook: Over 35 hands-on recipes to efficiently master the art of behaviour-driven development using Cucumber-JVM

eBook
$24.99 $35.99
Paperback
$43.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Cucumber Cookbook

Chapter 2. Creating Step Definitions

In this chapter, we will cover the following topics:

  • Creating your first Step Definitions file
  • Identifying duplicate and Ambiguous Step Definitions
  • Using regular expressions to optimize Step Definitions
  • Using Optional Capture/Noncapture groups
  • Transforming Data Tables to parse the test data
  • Implementing Data Table diffs to compare tables
  • Using Doc Strings to parse big data as one chunk
  • Combining Doc Strings and Scenario Outlines
  • Defining String transformations for better conversions

Introduction

Sometimes people who are not that well versed in Cucumber argue that creating a Step Definitions file is an overhead as compared to the frameworks that do not have Cucumber. But what they don't realize is that Cucumber auto-generates these Step Definitions, so it's not an overhead. With the knowledge of the concepts covered in this chapter, you will be able to write very effective and efficient Step Definitions.

In this chapter, we will start with the basic concepts of Glue Code/Step Definitions in detail by covering the different types of Step Definitions, the usage of regular expressions, and so on. To come up with optimized and efficient Step Definitions, we will also elaborate upon advanced concepts of Doc Strings, Data Table transformations, and Capture groups.

Creating your first Step Definitions file

Now let's assume you are an automation developer and you have to implement automated test cases for a Feature file. The next Step in this direction would be to write the Step Definitions for this Feature file. So, how do we write Step Definitions in a Cucumber project? Let's see how to do this in this recipe.

How to do it…

The easiest way to create Step Definitions is to let Cucumber take care of it. The Steps are as follows:

  1. Here is the Feature file used in our previous chapter. Let's use this Feature file to create our first Step Definitions:
    Feature: login Page
      In order to test login page
      As a Registered user
      I want to specify the login conditions
    
      Scenario: checking pre-condition, action and results
        Given user is on Application landing page
        When user clicks Sign in button
        Then user is on login screen
  2. When you save the Feature file and run (either via Eclipse or via a Terminal), Cucumber is going to give errors...

Identifying Duplicate and Ambiguous Step Definitions

Sometimes when we are writing Cucumber Step Definitions files, we get either Duplicate Step Definitions errors or Ambiguous Step Definitions errors. Let's try and understand the reasons why these errors arise, and how we can remove them through this recipe.

How to do it…

We will use the same Feature file from previous recipe. Perform the following Steps:

  1. Let's create one more class in the StepDefinitions package, called DuplicateAmbiguous.java, with the following content:
    package com.StepDefinitions;
    
    import cucumber.api.java.en.Given;
    
    public class DuplicateAmbiguous {
      
      //Duplicate Steps
      @Given("^user is on Application landing page$")
      public void user_is_on_Application_landing_page_duplicate() throws Throwable {
        //sample code goes here
        System.out.println("Duplicate");
      }
    
    }

    When you try to run the Feature file, observe the Cucumber output:

    Exception in thread "main" cucumber.runtime...

Using Regular Expressions to optimize Step Definitions

Until now, we have created Step Definitions with one-to-one relations with Steps. But this way of writing Step Definitions can be cumbersome as we write more and more Feature files. So, we will write generic Step Definitions that will apply to all the Steps that follow a certain pattern, thus bringing down the number of Step Definitions required. Let's see how to do this in this recipe.

How to do it…

  1. Let's assume we are writing Step Definitions for the following Scenario.
    Scenario: login fail - wrong username
        Given user is displayed login screen
        When user enters "wrongusername" in username field
        And user enters "123456" in password field
        And user clicks Sign in button
  2. Now run the Feature file, and copy and paste the Cucumber Step Definitions suggestions in the LoginSteps.java class. This is how LoginSteps.java looks:
    package com.StepDefinitions;
    
    import cucumber.api.java.en.Given;
    import...

Using Optional Capture and Noncapture Groups

Until now, we have covered how to write Step Definitions for various keywords in Feature files. Now let's talk about how we can efficiently use Step Definitions for multiple Steps.

Think about a situation where we are testing a positive situation in one Step and a negative situation in some other Step—the only difference in both Steps is just the word "No", while the remaining sentence is same. Based on the knowledge that we have acquired so far, we will write two Step Definitions for these two Steps. But is there a better way of doing this? Let's see how we can do this better in this recipe.

How to do it…

  1. For this recipe, consider the following Scenarios and focus on the highlighted text:
    Scenario: Optional Capture Groups/Alternation
        #positive
        Then I see following dollars in my account
        #negative
        Then I do not see following dollars in my account
       
        Scenario: Optional Non capture Groups
        Given...

Transforming Data Tables to parse the test data

In the previous chapter, we covered how Data Tables can be used to send large sets of data to a single Step. Now let's understand how to handle Data Tables in Step Definitions in this recipe.

How to do it…

  1. Let's assume we are writing Step Definitions for the following Scenario:
    Scenario: Existing user Verification
        Given user is displayed login screen
        Then we verify following user exists
          | Name    | Email           |
          | Shankar | [email protected] |
          | Ram     | [email protected]   |
          | Sham    | [email protected]  |
  2. Now run the Feature file, and copy paste the Cucumber Step Definitions suggestions in the LoginSteps.java class. These are the additional Steps in LoginSteps.java:
    @Then("^we verify following user exists$")
    public void we_verify_following_user_exists(DataTable arg1) throws Throwable {
        /* Write code here that turns the phrase above into 
        concrete actions
        For automatic transformation...

Introduction


Sometimes people who are not that well versed in Cucumber argue that creating a Step Definitions file is an overhead as compared to the frameworks that do not have Cucumber. But what they don't realize is that Cucumber auto-generates these Step Definitions, so it's not an overhead. With the knowledge of the concepts covered in this chapter, you will be able to write very effective and efficient Step Definitions.

In this chapter, we will start with the basic concepts of Glue Code/Step Definitions in detail by covering the different types of Step Definitions, the usage of regular expressions, and so on. To come up with optimized and efficient Step Definitions, we will also elaborate upon advanced concepts of Doc Strings, Data Table transformations, and Capture groups.

Creating your first Step Definitions file


Now let's assume you are an automation developer and you have to implement automated test cases for a Feature file. The next Step in this direction would be to write the Step Definitions for this Feature file. So, how do we write Step Definitions in a Cucumber project? Let's see how to do this in this recipe.

How to do it…

The easiest way to create Step Definitions is to let Cucumber take care of it. The Steps are as follows:

  1. Here is the Feature file used in our previous chapter. Let's use this Feature file to create our first Step Definitions:

    Feature: login Page
      In order to test login page
      As a Registered user
      I want to specify the login conditions
    
      Scenario: checking pre-condition, action and results
        Given user is on Application landing page
        When user clicks Sign in button
        Then user is on login screen
  2. When you save the Feature file and run (either via Eclipse or via a Terminal), Cucumber is going to give errors for the missing Step...

Identifying Duplicate and Ambiguous Step Definitions


Sometimes when we are writing Cucumber Step Definitions files, we get either Duplicate Step Definitions errors or Ambiguous Step Definitions errors. Let's try and understand the reasons why these errors arise, and how we can remove them through this recipe.

How to do it…

We will use the same Feature file from previous recipe. Perform the following Steps:

  1. Let's create one more class in the StepDefinitions package, called DuplicateAmbiguous.java, with the following content:

    package com.StepDefinitions;
    
    import cucumber.api.java.en.Given;
    
    public class DuplicateAmbiguous {
      
      //Duplicate Steps
      @Given("^user is on Application landing page$")
      public void user_is_on_Application_landing_page_duplicate() throws Throwable {
        //sample code goes here
        System.out.println("Duplicate");
      }
    
    }

    When you try to run the Feature file, observe the Cucumber output:

    Exception in thread "main" cucumber.runtime.DuplicateStepDefinitionException: Duplicate...

Using Regular Expressions to optimize Step Definitions


Until now, we have created Step Definitions with one-to-one relations with Steps. But this way of writing Step Definitions can be cumbersome as we write more and more Feature files. So, we will write generic Step Definitions that will apply to all the Steps that follow a certain pattern, thus bringing down the number of Step Definitions required. Let's see how to do this in this recipe.

How to do it…

  1. Let's assume we are writing Step Definitions for the following Scenario.

    Scenario: login fail - wrong username
        Given user is displayed login screen
        When user enters "wrongusername" in username field
        And user enters "123456" in password field
        And user clicks Sign in button
  2. Now run the Feature file, and copy and paste the Cucumber Step Definitions suggestions in the LoginSteps.java class. This is how LoginSteps.java looks:

    package com.StepDefinitions;
    
    import cucumber.api.java.en.Given;
    import cucumber.api.java.en.When;
    
    public...
Left arrow icon Right arrow icon

Description

This book is intended for business and development personnel who want to use Cucumber for behavior-driven development and test automation. Readers with some familiarity with Cucumber will find this book of most benefit. Since the main objective of this book is to create test automation frameworks, previous experience in automation will be helpful.

Who is this book for?

This book is intended for business and development personnel who want to use Cucumber for behavior-driven development and test automation. Readers with some familiarity with Cucumber will find this book of most benefit.

What you will learn

  • Explore the usage of the Gherkin Language to write meaningful and smart Feature files
  • Understand Scenario, Steps, Backgrounds, Scenario Outlines, and Data Tables
  • Discover the concepts of Glue Code and Step Definitions in detail
  • Gain insights into the different types of Step Definitions, Regular Expressions, Doc Strings, Data Table transformations, and Capture Groups
  • Master the advanced concepts of implementing Tags and Hooks
  • Override default Cucumber options and settings along with different output report formats
  • Run Jenkins and Cucumber from Terminal while running various Cucumber Scenarios in parallel

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jun 02, 2015
Length: 162 pages
Edition : 1st
Language : English
ISBN-13 : 9781785284137
Category :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Jun 02, 2015
Length: 162 pages
Edition : 1st
Language : English
ISBN-13 : 9781785284137
Category :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 92.98
Selenium Testing Tools Cookbook Second Edition
$48.99
Cucumber Cookbook
$43.99
Total $ 92.98 Stars icon
Banner background image

Table of Contents

7 Chapters
1. Writing Feature Files Chevron down icon Chevron up icon
2. Creating Step Definitions Chevron down icon Chevron up icon
3. Enabling Fixtures Chevron down icon Chevron up icon
4. Configuring Cucumber Chevron down icon Chevron up icon
5. Running Cucumber Chevron down icon Chevron up icon
6. Building Cucumber Frameworks Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.7
(3 Ratings)
5 star 0%
4 star 66.7%
3 star 33.3%
2 star 0%
1 star 0%
Mark Lindsay Aug 21, 2015
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
Cheap and cheerful book - did the job
Amazon Verified review Amazon
S Jul 29, 2015
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
Well written and clearly laid out..You have clearly articulated the Mobile testing and the REST API test aspects
Amazon Verified review Amazon
cappucappu Aug 14, 2015
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
Ich suchte nach einem Buch über Cucumber für Java für fortgeschrittene Anwender und war gespannt auf diese Neuerscheinung. Zwar werden viele Aspekte von Cucumber erwähnt, jedoch ist die Darstellung in Form von "Rezepten" nicht sonderlich gelungen. Die Erläuterungen sind häufig unzureichend und es haben sich auch kleinere Fehler eingeschlichen. Die Formulierungen der Szenarien (die Wort-, Satzwahl sowie der Inhalt) stellen meines Erachtens nach kein gutes Beispiel für gelungene Anforderungsdokumentation dar.Alles in allem hat das sicherlich dazu beigetragen, Wissen über Cucumber für Java zu vermitteln. Sprachlich und didaktisch ist noch "Luft nach oben".
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.