4

How can I use variable between the steps within one scenario in behat? I need to store the value of $output and then use it in the second step.

Let's say I have the following structure:

class testContext extends DefaultContext
{
    /** @When /^I click "([^"]*)"$/ */
    public function iClick($element) {
       if ($element = 2){
           $output = 5        
       }
    }


    /** @When /^I press "([^"]*)"$/ */
    public function iPress($button) {
        if($button == $output){
        echo "ok";
        }
    }
}
laechoppe
  • 232
  • 3
  • 14

1 Answers1

6

The context class can be stateful; all steps of a scenario will use the same context instance. This means that you can use regular class attributes to preverse state between steps:

class testContext extends DefaultContext
{
    private $output = NULL;

    /** @When /^I click "([^"]*)"$/ */
    public function iClick($element)
    {
       if ($element = 2) {
           $this->output = 5;
       }
    }


    /** @When /^I press "([^"]*)"$/ */
    public function iPress($button)
    {
        if ($this->output === NULL) {
            throw new BadMethodCallException("output must be initialized first");
        }

        if ($button == $this->output) {
            echo "ok";
        }
    }
}
helmbert
  • 35,797
  • 13
  • 82
  • 95