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

ix0qys7i  于 2023-11-20  发布在  其他
关注(0)|答案(6)|浏览(145)

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

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


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

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


但是我想使用Redirect::route。有没有办法让PHPUnit跟随重定向?

kqhtkvqz

kqhtkvqz1#

你可以让PHPUnit跟随重定向:

Modern 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。

cunj1qz1

cunj1qz12#

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

字符串
对我有用,希望有帮助。

wgeznvg7

wgeznvg73#

你可以告诉crawler以这种方式跟踪重定向:

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

tzdcorbm

tzdcorbm4#

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

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

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

字符串

z9zf31ra

z9zf31ra5#

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

字符串

4urapxun

4urapxun6#

对于Laravel 5.6,您可以设置

$protected followRedirects = true;

字符串
在测试用例的类文件中

相关问题