Behat Using Optional Capture Groups

Profile picture for user devraj

An Optional Capture group eliminates the duplication of Step Definitions and can definitely improve the readability of Feature files.

Same step definition can be used for both positive and negative assertion using option capture group. For example:

#Positive
Then I see "test" link
#Negative
Then I do not see "test" link

Above 2 steps definitions are similar but one is with positive assertion and another is with negative assertion. You might write 2 steps if you are not aware of captured groups.

/**
  * @Then I see :arg1 link
  */
public function iSeeLink($arg1)
{
}

/**
  * @Then I do not see :arg1 link
  */
public function iDoNotSeeLink($arg1)
{
}

You can convert these 2 step definition into one by using regular expressions

/**
  * @Then /^I (see|do not see) \"([a-zA-Z ]*)\" link$/
  */
  public function iSeeLink($option,$expected)
  {
    echo $option;
    echo "\n". $expected;
  }

Here we are capturing see or do not see  in $option variable and "test" in $expected variable.

  •    It denotes the start of string.
  • $    It denotes the end of string.
  • ()    It denotes a group of expressions.
  • []    It finds a range of characters for example [xyz] means x, y or z .
  • *    It denotes zero or more of preceding character or item range.
  • [a-z]    Any lowercase letter
  • [A-Z]    Any uppercase letter
  • \s    Matches space characters like space, newline or tab
  • | (pipe)    It is the logical OR for example x | y means x OR y.

We use pipe (|) to create optional group e.g ( see| do not see).

Tags