Laravel http 测试重定向到 \ 而不是登录

Laravel http test redirecting to \ instead of login

嗨,我正在 laravel 5.6 中尝试测试,但是当尝试像下面这样测试无效登录时

public function testInvalidLogin()
    {
        $response = $this->post('/login',[ 'email'=>'fake@email.com', 'password'=>'secret' ]);
        $response->assertStatus(302);
        $response->assertLocation('/login');
    }

但是当我 运行 这个时候我得到了错误

Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
-'http://localhost/login'
+'http://localhost'

D:\project\larademo\vendor\laravel\framework\src\Illuminate\Foundation\Testing\TestResponse.php:198
D:\project\larademo\tests\Feature\ExampleTest.php:38

FAILURES!
Tests: 3, Assertions: 5, Failures: 1.

我也用过 followingRedirects() 但它给出了响应代码 200 和“/”的内容

你能帮我看看这是怎么回事吗

EDIT :我希望它应该重定向到登录,因为当我在登录失败后在浏览器中使用时,它会重定向回登录页面,所以测试应该重定向到登录

assertLocation checks the Location header,其中 设置为 /,因为这是重定向指向的位置。

希望这个答案能为某人节省几个小时,我失去了 搜索信息,为什么这个测试失败...

Laravel,登录尝试失败后,将您重定向到 back() 而不是 /login 路由。发现在这个post:https://www.reddit.com/r/laravel/comments/8wc1na/laravel_http_test_redirecting_to_instead_of_login/

您可以通过 "simulating" 用户行为和 /登录 页面开始(在 Laravel 7.2.1):

public function test_user_is_redirected_back_to_login_page_after_failed_login()
{
    $user = factory(User::class)->create();

    $response = $this->get('/login');
    $response->assertStatus(200);

    $response = $this->post('/login', ['email' => $user->email, 'password' => 'wrong_pass']);
    $response->assertStatus(302);

    $response->assertRedirect('/login');
    $response->assertLocation('/login');
}

在研究时,我偶然发现了 Laravel Dusk。在我看来,如果你刚开始学习 Laravel 测试,那么学习 dusk 就太过分了。但是,至少在某个时候熟悉它可能是个好主意...

发生这种情况是因为您可能在无效登录时使用了 return 返回,其中测试用例返回指向 '/' URL,因此它将被重定向到该页面。为了克服这个问题,您可以使用@arty marty 解决方案,或者您可以将 from 路由附加到您的 post 请求,如下所示:

public function testInvalidLogin()
{
    $response = $this->from('/login')
                     ->post('/login',[ 
                           'email'=>'fake@email.com', 
                           'password'=>'secret' 
                     ]);
    $response->assertStatus(302);
    $response->assertLocation('/login');
}