Skip to main content

Cucumber Optional and Alternative Text

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:

  1. Optional Text
  2. Alternative Text

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() {
}

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 Alternative Text and Optional Text

Submitted by tgoswami on February 12, 2021

Tarun has 11+ years of experience in Quality Assurance in different domains like Banking, E-commerce, Health and Education.

About

At ProgramsBuzz, you can learn, share and grow with millions of techie around the world from different domain like Data Science, Software Development, QA and Digital Marketing. You can ask doubt and get the answer for your queries from our experts.