Behat Step Hooks

Profile picture for user devraj

Step hooks are triggered before or after each step runs. These hooks are executed inside an initialized FeatureContext instance, so they are just plain FeatureContext instance methods. 

There are two step hook types available:

@BeforeStep: executed before every step in each scenario.
@AfterStep: executed after every step in each scenario.

The hooks have "invoke around" semantics. Meaning that if a BeforeStep hook is executed the AfterStep hooks will also be executed regardless of the result of the step. If a step did not pass, the following step and its hooks will be skipped.

These 2 hooks are not used so frequently but there can be several application depending upon your usage:

  • collecting data - such as all external links
  • Screenshot after every step or if particular steps failed
/**
* @BeforeStep
*/
public static function beforeStep()
{
    echo "Before Step Executed";
}

/**
* @AfterStep
*/
public static function afterStep()
{
    echo "After Step Executed";
}

Before Step and After Step will execute for every step no matter whether it is in Background section or in Scenario section.

Tags