Search code examples
phpsymfonybehat

Behat reusable actions add header


I'm using Behat in a Symfony2 app.

I have made a reusable action to add a HTTP header on some scenarios

/**
* @Given I am authenticated as admin
*/
public function iAmAuthenticatedAsAdmin()
{
    $value = 'Bearer xxxxxxxxxxx';

    $response = new Response();
    $response->headers->set('Authorization', $value);
    $response->send();

    return $response;
 }

This action is call when I add the I am authenticated as admin step in my scenario but it doesn't add my header. Like this

Scenario: I find all my DNS zones
  Given I am authenticated as admin
  And I send a GET request to "/api/dns"
  Then the response code should be 200

How can I add a HTTP header before my request step in my scenario, using a reusable action ? Is it possible ?

Thank.


Solution

  • I have find the way to do this.

    If you are using WebApiExtension

    Just import the WebApiContext in your context class like this

    /**
     * @param BeforeScenarioScope $scope
     *
     * @BeforeScenario
     */
    public function gatherContexts(BeforeScenarioScope $scope)
    {
        $environment = $scope->getEnvironment();
    
        $this->webApiContext = $environment->getContext('Behat\WebApiExtension\Context\WebApiContext');
    }
    

    And you just have now to use the iSetHeaderWithValue :

    /**
     * @Given I am authenticated as admin
     */
    public function iAmAuthenticatedAsAdmin()
    {
        $name = 'Authorization';
        $value = 'Bearer xxxxxxxx';
    
        $this->webApiContext->iSetHeaderWithValue($name, $value);
    }