Laravel - Testing what happens after a redirect(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' => 'test@test.com', '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' => 'john@example.com'])
->assertStatus(200);
注意:这需要为每个请求明确设置.
对于这两者之间的版本:
参见 https://github.com/laravel/framework/issues/18016#issuecomment-322401713 了解解决方法.
See https://github.com/laravel/framework/issues/18016#issuecomment-322401713 for a workaround.
这篇关于Laravel - 测试重定向后会发生什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Laravel - 测试重定向后会发生什么


基础教程推荐
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- 如何替换eregi() 2022-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01