Laravel - 测试重定向后会发生什么

问题描述 投票:0回答:6

我有一个控制器,在提交电子邮件后,执行重定向到主页,如下所示:

return Redirect::route('home')->with("message", "Ok!");

我正在为其编写测试,我不确定如何使 phpunit 遵循重定向,以测试成功消息:

public function testMessageSucceeds() {
    $crawler = $this->client->request('POST', '/contact', ['email' => '[email protected]', 'message' => "lorem ipsum"]);

    $this->assertResponseStatus(302);
    $this->assertRedirectedToRoute('home');

    $message = $crawler->filter('.success-message');

    // Here it fails
    $this->assertCount(1, $message);
}

如果我用控制器上的代码替换它,并删除前 2 个断言,它就可以工作

Session::flash('message', 'Ok!');
return $this->makeView('staticPages.home');

但我想用

Redirect::route
。有没有办法让 PHPUnit 遵循重定向?

php redirect laravel phpunit
6个回答
62
投票

您可以让 PHPUnit 遵循重定向:

现代 Laravel(>= 5.5.19):

$this->followingRedirects();

旧版 Laravel (< 5.4.12):

$this->followRedirects();

用途:

$response = $this->followingRedirects()
    ->post('/login', ['email' => '[email protected]'])
    ->assertStatus(200);

注意: 需要为每个请求明确设置。


对于这两个之间的版本

请参阅 https://github.com/laravel/framework/issues/18016#issuecomment-322401713 了解解决方法。


11
投票

Laravel 8 已测试

$response = $this->post'/contact', ['email' => '[email protected]', 'message' => "lorem ipsum"]);

$response->assertStatus(302);
$response->assertRedirect('home');

$this->followRedirects($response)->assertSee('.success-message');
//or
$this->followRedirects($response)->assertSee('Ok!');

为我工作,希望有帮助。


8
投票

您可以告诉爬虫以这种方式遵循重定向:

$crawler = $this->client->followRedirect();

所以在你的情况下会是这样的:

public function testMessageSucceeds() {
    $this->client->request('POST', '/contact', ['email' => '[email protected]', 'message' => "lorem ipsum"]);

    $this->assertResponseStatus(302);
    $this->assertRedirectedToRoute('home');

    $crawler = $this->client->followRedirect();

    $message = $crawler->filter('.success-message');

    $this->assertCount(1, $message);
}

4
投票

从 Laravel 5.5 开始测试重定向,你可以使用 assertRedirect:

/** @test */
public function store_creates_claim()
{
    $response = $this->post(route('claims.store'), [
        'first_name' => 'Joe',
    ]);

    $response->assertRedirect(route('claims.index'));
}

0
投票
//routes/web.php
Route::get('/', function () {
    return redirect()->route('users.index');
})->name('index');


//on my TestClass
$response = $this->get('/');


$response->assertStatus(302);
$response->assertRedirect(route('users.index'));


-4
投票

对于 Laravel 5.6,可以设置

$protected followRedirects = true;

在您的测试用例的类文件中

© www.soinside.com 2019 - 2024. All rights reserved.