How to Pass Null or Empty Values From Behat Scenario Outline Examples?

Learn how to pass null or empty values to a Behat step definition method from a scenario outline

A Behat scenario outline is a great way to test different values with the same steps. However, passing empty or null values to a step method from scenario outline examples can be a little tricky as it only passes a string to the step definition method.

Let's suppose we have the following scenario outline:

Scenario Outline: Invalid input values should throw validation error
  Given I am on the signup form page
  When I input "<value>" into the email field
  And I click on the submit button
  Then I should see a validation error

  Examples:
    | value        |
    |              |
    | NULL         |
    | "no-domain"  |

Please note that if behat reports the empty value as "undefined" then it maybe because of one of the following reasons:

  • You forgot to wrap your placeholder within double quotes (e.g. "<value>"), or;
  • The regular expression in your step definition method ignores it, or;
  • Your version of behat lacks support for passing empty values from scenario outline examples.

In case you suspect that behat lacks support for it (or you're on the verge of giving up), then you could instead use a placeholder (such as "N/A") to denote an empty value.

Now, in your step definition method, you could convert the "special cases" (such as "NULL", "N/A", etc.) into the correct types. For example:

/**
 * @When /^I input "([^"]*)" into the email field$/
 */
public function iEnterEmail(string $email)
{
    if ($email === 'NULL') {
        $email = null;
    }

    // ...
}

However, if you need to re-use the null type in other step definition methods as well, then it might be a good idea to use the @Transform annotation to convert "NULL" string into the null type like so:

/**
 * @Transform /^NULL$/i
 */
public function transformNull()
{
    return null;
}

In this way, the step definition method will be served the right type.

Remember to update the type hints of your step definition method arguments if you expect non-string types.


Hope you found this post useful. It was published . Please show your love and support by sharing this post.