You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Behat重定向时追加额外URL问题求助(Symfony3.4+FOSUserBundle环境)

解决Behat Mink重定向时追加额外URL的问题

我之前在Symfony 3.x搭配Behat Mink做验收测试时也碰到过一模一样的问题——当测试外部域名重定向时,Mink的Symfony2驱动会自动把base_url拼接到目标URL前面,导致出现类似http://my-virutalhost.test/http://some-page-here.com的错误拼接地址。下面是几个经过验证的解决办法:

1. 切换到Selenium2(JavaScript)会话测试外部重定向

Symfony2驱动本身是在内部模拟请求,不会真正发起外部HTTP请求,所以它处理外部域名重定向时会默认拼接base_url。你已经配置了javascript会话,只需要在场景里指定使用这个会话:

Scenario: I execute endpoint address with wrong redirect code
  Given I am using the "javascript" session
  When I go to the url "/redirect/code1code2"
  Then I should be redirected to url "http://some-page-here.com"

Selenium会真正打开浏览器发起请求,能正确处理跨域名的重定向,不会追加额外的base_url。

2. 自定义断言处理重定向URL

如果你不想用Selenium(比如追求测试速度),可以自定义一个Behat步骤来手动校验响应头里的Location值,绕过Mink默认的URL拼接逻辑:

首先在你的FeatureContext类中添加这个步骤方法:

/**
 * @Then I should be redirected to external url :url
 */
public function iShouldBeRedirectedToExternalUrl($url)
{
    $response = $this->getSession()->getDriver()->getClient()->getResponse();
    $location = $response->headers->get('Location');
    
    if ($location !== $url) {
        throw new \Exception(sprintf('Expected redirect to "%s", but got "%s"', $url, $location));
    }
}

然后修改测试场景使用自定义断言:

Scenario: I execute endpoint address with wrong redirect code
  When I go to the url "/redirect/code1code2"
  Then I should be redirected to external url "http://some-page-here.com"

这个方法直接读取Symfony响应头里的原始Location值,完全避免Mink的URL补全行为。

3. 检查重定向逻辑的实现

最后也可以排查一下你的/redirect/code1code2接口的重定向代码,确保返回的是完整的外部URL,而不是相对路径。比如在Symfony控制器里应该这样写:

// 正确:返回完整外部域名URL
return $this->redirect('http://some-page-here.com', 302);

不要写成省略域名的相对路径,否则Mink会自动补全base_url导致拼接错误。


内容的提问来源于stack exchange,提问作者emailnabyleco

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 12:17:29