ikucheriavenko
6/5/2017 - 7:51 PM

Accessing other contexts in Behat 3

Accessing other contexts in Behat 3

Feature: SubContext
  Scenario: Access the sub context
    When I set the state "foo"
    Then the state should be "foo"
default:
  suites:
    default:
      contexts: [FeatureContext, SubContext]
<?php

use Behat\Behat\Context\Context;

class SubContext implements Context {
    private $state;

    function setState($state) {
        $this->state = $state;
    }

    /** @Then the state should be :state */
    function theStateShouldBe($state) {
        PHPUnit_Framework_Assert::assertSame($state, $this->state);
    }
}
<?php

use Behat\Behat\Context\Context;
use Behat\Behat\Hook\Scope\BeforeScenarioScope;

class FeatureContext implements Context {
    private $subContext;

    /** @BeforeScenario */
    public function gatherContexts(BeforeScenarioScope $scope)
    {
        $environment = $scope->getEnvironment();
    
        $this->subContext = $environment->getContext('SubContext');
    }

    /** @When I set the state :state */
    function IGetTheContext($state) {
        $this->subContext->setState($state);
    }
}