Behat 可重用操作添加标头


Behat reusable actions add header

我在Symfony2应用程序中使用Behat。

我做了一个可重用的操作,在某些情况下添加HTTP标头

/**
* @Given I am authenticated as admin
*/
public function iAmAuthenticatedAsAdmin()
{
    $value = 'Bearer xxxxxxxxxxx';
    $response = new Response();
    $response->headers->set('Authorization', $value);
    $response->send();
    return $response;
 }

当我在方案中添加I am authenticated as admin步骤时,将调用此操作,但它不会添加标头。喜欢这个

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

如何使用可重用操作在我的方案中的请求步骤之前添加 HTTP 标头?可能吗?

谢谢。

我已经找到了做到这一点的方法。

如果您使用的是 WebApiExtension

只需像这样在上下文类中导入 WebApiContext

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

您现在只需要使用iSetHeaderWithValue

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

为什么不简单地将其存储在会话中(提示:会话应该在每个场景中被销毁;请查看BeforeScenario)并在需要时使用它?

因为我想它已添加,但在下一个请求中,随着一对全新的请求/响应的生成,它就消失了(如果我正确理解您的需求)