Cucumber Optional Capture Groups

Profile picture for user devraj

Consider a situation where you test a positive case in one step and a negative one in other. For example

#positive
Then I should see the "Log Out" link

#negative
Then I should not see the "Log Out" link

In the above example, the difference between the two steps is that we have an additional word, not in the second step. 

In Cucumber, if two or more steps differ from each other with one or two words. And you have to make the decision based on those words; you can create a single-step definition for steps and use conditional logic inside your step definitions.

Cucumber Optional Parameter Java

Both Negative and Positive will call below Step Definition

@Then("^I (should|should not) see \"([\\w\\s]+)\" link$")
public void i_should_not_see_link(String optionalValue, String linkText) 
{
    Boolean expectedValue = false;
    Boolean linkPresent = driver.findElements(By.linkText(linkText)).size() > 0;
	
    if(optionalValue.equals("should not"))
        expectedValue = false;
    else if(optionalValue.equals("should"))
        expectedValue = true;
		
    Assert.assertEquals(expectedValue, linkPresent);
}
  • (): When you surround part of a regular expression with parentheses, it becomes a capture group.
  • |: The use of a pipe between parentheses creates an optional group. Here, more than two options can also be grouped.
  • We are capturing value should or should not and receiving them in optionalValue parameter.
  • Here if size() value is greater than 0 that means element is present otherwise not.

Using Optional Capture Group you can avoid creating duplicate steps and improve the readability of Feature file.

Video Tutorial: Cucumber Optional Capture Group