route() not working with Route::enableFilters()



我正在使用单元测试我的应用程序,并且在尝试使用TestCase::callSecure()route()助手调用控制器操作时会得到NotFoundHttpException

对于这些测试(只有少数),我还使用Route::enableFilters启用了过滤器。

我的filters.php:

App::before(
    function ($request) {
        // force ssl
        if (!$request->isSecure())
        {
            return Redirect::secure($request->getRequestUri());
        }
    }
);
// some authentication
Route::filter('auth.api', 'Authentication');

我的路由:

Route::post('login', array('as' => 'login', 'uses' => 'AuthenticationController@login'));
Route::post('register', array('as' => 'register', 'uses' => 'AuthenticationController@register'));

示例测试我得到例外:

$credentials = [
    // ...
];
$response = $this->callSecure('POST', route('login'), $credentials);

当我通过他们的路径调用这些动作时,它可以正常工作。

$credentials = [
    // ...
];
$response = $this->callSecure('POST', '/login', $credentials);

这是打算还是错误?

route(Route()助手将为给定的路由生成一个URL(包括相关协议,即HTTP/S)。在您的情况下,它将返回类似的东西:

https://example.com/login

这不是您想要的。当您要执行重定向时,这很有用:

Redirect::route('login');

因此,您在上一个示例中所做的是做自己想做的事情的正确方法;由于您不想将完整的URL作为参数传递给您的callecure()函数。

$response = $this->callSecure('POST', '/login', $credentials);

正如戴夫(Dave)所提到的,您可以使用url ::路由来生成相对URL,并传递默认为 true$absolute参数。例如,使用命名路由时,您可以使用以下内容:

$route = URL::route('profile', array(), false);

将生成一个相对URL,例如/profile

route()助手不会创建相对URL,这是您真正想要的。

要生成一个相对URL,您可以使用URL::route,因为它允许您传递默认为true的$absolute参数。因此,要使用命名路线获得相对URL,您可以做

$credentials = [
// ...
];
$route = URL::route('login', array(), false);
$response = $this->callSecure('POST', $route, $credentials);

虽然'/login'方法正确,但如果您仍然必须在决定更改它的情况下/时,它会失败使用指定路线的目的。

最新更新