沃梦达 / 编程问答 / php问题 / 正文

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

Laravel - Testing what happens after a redirect(Laravel - 测试重定向后会发生什么)

本文介绍了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 - 测试重定向后会发生什么

基础教程推荐