Search code examples
phpbddbehat

Behat3 Subcontexts


Previous versions of Behat used useContext to include subcontexts and execute them. My question is how can I include SubContext in Behat3 ?

I tried looking into Behat3 documentation but it looks like the link is broken, also tried searching stackoverflow but still no clue.


Solution

  • You can do something like

    //behat.yml
    default:
      suites:
        default:
          contexts: [FeatureContext, SubContext]
    

    //FeatureContext.php
    <?php
    
    use Behat\Behat\Context\Context;
    use Behat\Behat\Hook\Scope\BeforeScenarioScope;
    
    class FeatureContext implements Context {
        private $subContext;
    
        /** @BeforeScenario */
        public function fetchContexts(BeforeScenarioScope $scope)
        {
            $environment = $scope->getEnvironment();
    
            $this->subContext = $environment->getContext('SubContext');
        }
    
        /** @When I do something on :foo */
        function IDoSomethingOnFoo($foo) {
            $this->subContext->doSomethingOnFoo($foo);
        }
    }
    

    //SubContext.php
    <?php
    
    use Behat\Behat\Context\Context;
    
    class SubContext implements Context {
    
        function doSomethingOnFoo($foo) {
            //...
        }
    }
    

    I didn't tested it but I'm pretty confident that this will answer to your question.