测试重定向后会发生什么

测试重定向后会发生什么

本文介绍了Laravel-测试重定向后会发生什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个控制器,在提交电子邮件后,将重定向到家庭,如下所示:

I have a controller that after submitting a email, performs a redirect to the home, like this:

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

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

I am writing the tests for it, and I am not sure how to make phpunit to follow the redirect, to test the success message:

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个断言,它将起作用

If I substitute the code on the controller for this, and I remove the first 2 asserts, it works

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

但是我想使用Redirect::route.有没有一种方法可以使PHPUnit遵循重定向?

But I would like to use the Redirect::route. Is there a way to make PHPUnit to follow the redirect?

推荐答案

您可以使PHPUnit遵循以下重定向:

You can get PHPUnit to follow redirects with:

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 解决方法.

这篇关于Laravel-测试重定向后会发生什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 15:07