Search code examples
regexbehat

Behat featurecontext reusable action regex issue


I'm trying to write a function in my feature context with an optional part in the action.

/**
* Function to scroll into view.
*
* @When /^I scroll "([^"]*)" into view( of type "([^"]*)")?$/g
*/
public function iScrollIntoView($locator, $type = "id") {
    // Some logic here.
}

So the idea is I can use in my behat script either: I scroll "foo" into view or I scroll "foo" into view of type "bar"

So I want the type part to be optional, while the regex seems to work fine in an online regex tester, it doesn't seem to work in my behat script.

When I put And I scroll "foo" into view in my behat script it doesn't recognise the function. Is there something wrong with my regex? Or is this a behat issue.


Solution

  • After some hard thinking the solution was quite logic. The main issue that caused behat to fail was the global => gin the regex, so after removing it behat was recognising the action.

    /**
    * Function to scroll into view.
    *
    * @When /^I scroll "([^"]*)" into view( of type "([^"]*)")?/
    */
    

    Second issue was the grouping, in my function I was using the second group as my parameter, however this is the group of the optional (of type "foo") and was not actually the variable of that group. So after adding a third parameter to the function I was able to retrieve it.

    public function iScrollIntoView($locator, $of_type_provided = FALSE, $type = "id") {
        // Some logic here.
    }
    

    I hope this is useful for some one else in the future.