Laravel 5.7成功登录后重定向到,出现测试问题

时间:2019-02-07 17:21:01

标签: laravel authentication redirect

登录后,我正在测试该用户是否重定向到/dashboard网址。

这是我的LoginController.php

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/dashboard';
    [...]

这是我的考验:

/**
     * Test that a logged user cannot view login
     *
     * @return void
     */
    public function test_logged_user_cannot_view_login_form()
    {
        $user = factory(User::class)->make();
        $response = $this->actingAs($user)->get('/');
        $response->assertRedirect('/dashboard');

    }

失败,phpunit抱怨

Failed asserting that two strings are equal.
Expected :'http://localhost/dashboard'
Actual   :'http://localhost/home'

实际上,如果我针对“ / home”进行测试,则测试成功。

但是,实际上,正确的登录按预期重定向到/dashboard而不是home

我该如何解决?

1 个答案:

答案 0 :(得分:1)

请确保这也反映在您的RedirectIfAuthenticated中间件中,因为actingAs()已登录用户。

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;

class RedirectIfAuthenticated
{
    /**
    * Handle an incoming request.
    *
    * @param  \Illuminate\Http\Request  $request
    * @param  \Closure  $next
    * @param  string|null  $guard
    * @return mixed
    */
    public function handle($request, Closure $next, $guard = null)
    {
        if (Auth::guard($guard)->check()) {
            return redirect('/dashboard');
        }

        return $next($request);
    }
}