Behat: getContext() function missing from Environment class

Created on 5 Jul 2018  路  1Comment  路  Source: Behat/Behat

I use a scenario hook to inject an authentication header when performing certain requests.
Although it works well (the header is correctly set) the IDE notifies me the getContext() function is missing. I checked in the class and indeed there is no getContext() function.

Here is my function

    public function login(BeforeScenarioScope $scope)
    {
        $scope->getEnvironment()->getContext(RestContext::class)->iAddHeaderEqualTo('Authorization', "Bearer $this->token");
    }

The Environment class namespace is Behat\Testwork\Environment
The behat version is 3.4

Am I missing something? I actually don't understand how the header can be added as it doesnt look like the function exists.

Most helpful comment

It's because BeforeScenarioScope::getEnvironment() is documented as returning an object implementing the Behat\Testwork\Environment\Environment interface.

However, at runtime it is most likely returning an instance of the Behat\Behat\Context\Environment\InitializedContextEnvironment class, which has extra methods including getContext. This is fine in a dynamically typed language like PHP.

If you want to be extra type-safe you can do:

public function login(BeforeScenarioScope $scope)
{
    $env = $scope->getEnvironment();

    if($env instanceof InitializedContextEnvironment) {
        $env->getContext(RestContext::class)->iAddHeaderEqualTo('Authorization', "Bearer $this->token");
    }
}

>All comments

It's because BeforeScenarioScope::getEnvironment() is documented as returning an object implementing the Behat\Testwork\Environment\Environment interface.

However, at runtime it is most likely returning an instance of the Behat\Behat\Context\Environment\InitializedContextEnvironment class, which has extra methods including getContext. This is fine in a dynamically typed language like PHP.

If you want to be extra type-safe you can do:

public function login(BeforeScenarioScope $scope)
{
    $env = $scope->getEnvironment();

    if($env instanceof InitializedContextEnvironment) {
        $env->getContext(RestContext::class)->iAddHeaderEqualTo('Authorization', "Bearer $this->token");
    }
}
Was this page helpful?
0 / 5 - 0 ratings

Related issues

mdrost picture mdrost  路  4Comments

beeblebrox3 picture beeblebrox3  路  8Comments

iongion picture iongion  路  8Comments

patxi1980 picture patxi1980  路  9Comments

Yogarine picture Yogarine  路  10Comments