4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

リダイレクト先のエラーメッセージをテストする

Posted at

Laravelのテンプレート内では常に$errorsという変数が定義されていて、Redirect::to(...)->withErrors($validator)などとしたときにエラーの内容がSessionStore経由でリダイレクト先にセットされる。この処理はIlluminate\View\ViewServiceProvider#registerSessionBinder()で、bootedイベントリスナーとして登録されている。

TestCaseはデフォルトではリダイレクトをfollowしないが、BrowserKitのfollowRedirect()を呼び出すことでfollowすることができる。

    $form = $this->client->getCrawler()->selectButton("Submit")->form();
    $this->client->submit($form);
    $this->client->followRedirect();

これを使ってリダイレクト先でエラーメッセージが表示されることをテストできるかと思ったのだが、この時bootedイベントリスナーは呼び出されないため、$errorsはセットされない。結果、ブラウザでテストするとエラーメッセージは表示されるがTestCaseからは見えない。

このため、エラーメッセージをテストするにはセッションの内容を確認するのが妥当のようだ。

    $this->assertSessionHas('errors');
    $this->assertSessionHasErrors(['email', 'password']);
    $this->assertSessionHasErrors(['name' => 'The name field is required.']);
4
3
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
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?