route()不使用Route :: enableFilters()

时间:2014-01-21 07:31:29

标签: php unit-testing routing laravel-4

我正在对我的应用进行单元测试,并在尝试使用NotFoundHttpExceptionTestCase::callSecure()帮助器调用控制器操作时获得route()

对于那些测试(只有少数),我还启用了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');

我的routes.php:

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);

这是故意还是错误?

2 个答案:

答案 0 :(得分:2)

route()帮助器将为给定的命名路由生成URL(包括相关协议,即http / s)。在您的情况下,它会返回类似的内容:

  

https://example.com/login

这不是你想要的。当您想要执行重定向时,这非常有用,例如:

Redirect::route('login');

所以你在上一个例子中所做的就是做你想做的事的正确方法;因为您不想将完整的URL作为参数传递给您的callSecure()函数。

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

正如dave所提到的,您可以使用URL :: route生成相对URL,并传递$absolute参数,默认为true。例如,使用命名路由时,您可以使用以下命令:

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

这会生成相对网址,例如/profile

答案 1 :(得分:0)

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

要生成相对网址,您可以使用URL::route,因为它允许您传递默认为true的$absolute参数。因此,要使用命名路径获取相对URL,您可以执行

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

虽然'/login'方法是正确的,但如果你决定改变它,你仍然需要搜寻你拥有该URL的所有地方,这会使得使用命名路由失败。

相关问题