LoginSignup
19
10

More than 3 years have passed since last update.

LaravelでリダイレクトテストするとルートURLが返ってきてしまう

Last updated at Posted at 2019-10-20

Laravel で、->assertredirect() を使ってPOST後に指定したページにリダイレクトできているかテストしようとした。
画面上では問題なく動作するのに、テストでは想定外のURLにリダイレクトしてしまう現象が起こり、少しハマった。

環境

Laravel 6.2.0

うまくいかなかったテスト

記事を投稿をするテスト


public function testCreatePost()
    {
        $response = $this
            ->post('post/create', [
                'title' => 'sample title'
                'text' => 'sample text'
            ])

        $response->assertRedirect('posts');
    }

テスト結果

There was 1 failure:

1) Tests\Feature\PostTest::testCreatePost
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
-'https://localhost/posts'
+'https://localhost'

画面上の動作でははちゃんと /posts にリダイレクトされてるのに、なぜルートURLに飛ばされることになってる??

原因

リダイレクトテストをしたとき、back() で前の画面に戻されるが、テストの仕様上、前の画面は保存されていない。
よって、ルートURLの https://localhost が返されてしまう。

対策

->from() で前の画面を指定(リファラーを定義)する必要があった。

public function testCreatePost()
    {
        $response = $this
            ->from('posts') //追加
            ->post('post/create', [
                'title' => 'sample title'
                'text' => 'sample text'
            ])

        $response->assertRedirect('posts');
    }

これでうまくテストが通った!

19
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
19
10