Skip to main content

If you are an expert, you might be writing your step definition by hand, but writing all these method stubs, annotations and patterns by hand is still tedious even if you are very good with Behat and PHP.

Behat makes this routine task much easier and fun by generating definition snippets for you! Let’s pretend that you have this feature:

@mysample
Scenario: Sample scenario
    Given step with "string" argument
    And number step with 25

 Now the moment you will type

$ behat --tags mysample

Behat will auto-generate 2 step definitions or snippets for you in console or terminal.

/**
  * @Given step with :arg1 argument
  */
public function stepWithArgument($arg1)
{
    throw new PendingException();
}

/**
  * @Given number step with :arg1
  */
public function numberStepWith($arg1)
{
    throw new PendingException();
}

It not only generates the proper definition annotation type (@Given), but also a proper pattern with tokens capturing (:arg1, :arg2), method name (stepWithArgument(), numberStepWith()) and arguments ( $arg1, $arg2), all based just on the text of the step. Isn’t that cool?

The only thing left for you to do is to copy these method snippets into your FeatureContext class and provide a useful body for them.

The interesting thing here is that you can save this copy paste time also. Earlier we use to implement SnippetAcceptingContext and CustomSnippetAcceptingContext which are deprecated now. But if you will use --append-snippets along with your command it will automatically add snippets inside your context class.

$ behat --tags mysample --append-snippets

You will see following output in console after executing above command:

u features/bootstrap/FeatureContext.php - `step with "string" argument` definition added
u features/bootstrap/FeatureContext.php - `number step with 23` definition added

 You can check you context file to see snippets are added or not.

Video Tutorial

Tags

About

Elix is a premium wordpress theme for portfolio, freelancer, design agencies and a wide range of other design institutions.