Cucumber Optional and Alternative Text

Profile picture for user devraj

There is no need to write a new step definition in Cucumber if your step differs by synonyms or singular plural. You can reduce lots of effort by using the Cucumber and Regular Expression technique. In this article, we will discuss two such strategies of Cucumber Expressions: Optional Text and Alternative Text.

Table of Contents

  1. Cucumber Optional Text
  2. Cucumber Alternative Text
  3. Video Tutorial

Cucumber Optional Text

Sometimes you have 1 item in your cart or more than one. It is grammatically incorrect to write "I have 1 items in cart" or "I have 2 item in cart," which we generally do to avoid creating duplicate step definitions. In such cases, you can make the plural s optional using Optional Text in Cucumber Expressions by using Round Brackets (). You can have one Step Definition for below two steps:

Then I have 1 item in cart
Then I have 2 items in cart

Step Definition

@Then("I have {int} item(s) in cart")	
public void teststep3() {
}

Cucumber Alternative Text

Consider a case when someone writes a product instead of the item in your step. Again, you don't need to create a new step definition; you can use the forward-slash (/) in your step definition to relax your language. For Example, below four steps you can map to single Step Definitions.

Then I have 1 item in cart
Then I have 1 product in cart
Then I have 2 items in cart
Then I have 2 products in cart

Step Definition

@Then("I have {int} item(s)/product(s) in cart")	
public void teststep3() {
}

Video Tutorial: Cucumber Optional and Alternative Text