如何在Laravel 4.1中对auth过滤器进行单元测试? [英] How do i unit test the auth filter in Laravel 4.1?

查看:138
本文介绍了如何在Laravel 4.1中对auth过滤器进行单元测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个单元测试,该测试应该检查未经身份验证的用户是否可以查看用户列表(他不应该能够查看该列表).

I want to write a unit test that should check if an unauthenticated user can view the user list (which he shouldnt be able to).

我的路线

Route::group(array('prefix' => 'admin'), function() {
    Route::get('login', function() {
        return View::make('auth.login');
    });
    Route::post('login', function() {
        Auth::attempt( array('email' => Input::get('email'), 'password' => Input::get('password')) );
        return Redirect::intended('admin');
    });
    Route::get('logout', 'AuthController@logout');

    Route::group(array('before' => 'auth'), function() {
        Route::get('/', function() {
            return Redirect::to('admin/users');
        });
        Route::resource('users', 'UsersController');
    });
});

我的测试

public function testUnauthenticatedUserIndexAccess() {
    $response = $this->call('GET', 'admin/users');

    $this->assertRedirectedTo('admin/login');
}

我的过滤器

Route::filter('auth', function() {
    if (Auth::guest()) return Redirect::guest('admin/login');
});

结果

未能断言Illuminate \ Http \ Response对象(...)是类"Illuminate \ Http \ RedirectResponse"的实例.

Failed asserting that Illuminate\Http\Response Object (...) is an instance of class "Illuminate\Http\RedirectResponse".

如果我从测试中记录了$ response,它会显示完整的用户列表,就像在测试期间登录了管理员一样.

If i log the $response from the test, it shows the full user list like if an admin was logged in during testing.

如果我在未登录的情况下使用浏览器浏览至管理员/用户,我将被重定向至登录状态,因此auth过滤器确实可以正常工作.

If i browse to admin/users using a browser without logging in I'm redirected to login like i should, so the auth filter is indeed working.

问题

  1. Laravel中是否有默认情况下在您测试期间登录第一位用户的内容?还是在测试过程中默认情况下Auth :: guest()始终为假?
  2. 如果是这样,我如何在单元测试期间被注销"?我试过$ this-> be(null),但收到一条错误消息,说传递的对象必须实现UserInterface.

推荐答案

对于单元测试,Laravel过滤器会自动禁用;您需要针对特定​​的测试用例启用它们.

Laravel filters are automatically disabled for unit tests; you need to enable them for a specific test case.

Route::enableFilters();

或者如果您不喜欢使用静态外墙,则可以这样做

Or this if you're not keen on using the static facades

$this->app['router']->enableFilters();

查看单元测试文档.

您的测试现在应该返回正确的对象类型,以使您的测试通过.

Your test should now return the correct object type allowing your test to pass.

这篇关于如何在Laravel 4.1中对auth过滤器进行单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆