Behat Using Optional Non-Capturing Groups

Profile picture for user devraj

In Optional Capture group we have different conditions for positive and negative cases that's why we have to received values as argument but in case of Optional Non-Capture there is no need to receive values in arguments.

For example: 

When I follow "test" link
When He follows "test" link
When User follow "test" link
When She follows "test" link

The corresponding step definition will be:

  * @When /^(?:I|She|He|User) follow(?:s)? \"([a-zA-Z\s]*)\" link$/
public function iFollowLink($arg1)

Notice, The addition of ?: to the beginning of Optional Capture groups creates optional non-Capture groups. Having ?: will treat the group as optional. Also, in some sentences you will use follow and sometime follows, that's why ?: is used after follow because s is optional.

You can use a non-capturing group to retain the organisational or grouping benefits but without the overhead of capturing. So, you do not need to pass an argument as described earlier with optional captured groups.

Consider another example:

When I select 2nd item
When I select 11th item
When I select 21st item

Here nd, th, st means nothing for us, all that we need to focus is 2, 11 and 21. Step definition will be this:

  * @When /^I select (?:[0-9]+)(?:st|nd|rd|th)? item$/
public function iSelectStItem()

Try to remove ? in the end, you will see it is not accepting value 2, 11 or 21 without using corresponding nd, th or st. When you write a non-capturing group that you want to be optional, it's easy to forget the final ?. then the expression will accept any of the alternative suffixes (-st, -nd etc), but including one of the suffixes will be mandatory for the expression to match. Don't confuse the ?: placed at the start of a non-capturing group with the optionality operator ?, placed after a group or item in the expression.