Search code examples
regexbehatgherkin

behat, gherkin and regex: using "not" or not


I have behat conditions which I want to cover with on function, using "not": Given this is happening and Given this is NOT happening. I can't find a regular expression that works though.

Here is what I'd like to achieve:

/**
 * @Given /^this is<regexCheckingNOT> happening$/
 */
public function thisIsHappening($not)
{
    if ($not) {
        // do this
    }

    // do that anyway
}

I tried these without success:

  • @Given /^this is(? NOT| ) happening$/
  • @Given /^this is( )?(NOT)? happening$/

and I cannot find a way to do this.


Solution

  • You can accomplish what you're trying to do by making " not" optional:

    /**
     * @Given /^this is( not)? happening$/
     */
    public function thisIsHappening($not = null)
    {
        if (null !== $not) {
            // do this
        }
    
        // do that anyway
    }
    

    You'll need to provide a default value (i.e. null) as this argument will not be present for the "this is happening" step.

    However, I'd consider making this two separate methods to make them simpler:

    /**
     * @Given this is happening
     */
    public function thisIsHappening()
    {
        // do that anyway
    }
    
    /**
     * @Given this is not happening
     */
    public function thisIsNotHappening()
    {
        // do this
    
        // do that anyway if you need something to happen in both cases
        $this->thisIsHappening();
    }