1
1

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 3 years have passed since last update.

【Laravel】Unitテストでユーザー認証をさせる

Last updated at Posted at 2021-03-19

はじめに

業務で既存のアプリケーションに通知機能を追加することになり、その途上のFeatureテストで便利なヘルパーがあることを知った
ので、そのメモです!

actingAsヘルパメソッドを使って現在認証済みのユーザーを指定させる(基本文法)


        $user = factory(User::class)->create(); // ユーザーモックを作り

        $response = $this->actingAs($user) // actingAsヘルパーで認証

使うことになったきっかけ

既存のコントローラに通知オブジェクトのcreate処理ロジックを組み込むため、その部分のテストを書いた。
しかし、そのpost操作の際にユーザー認証ができておらず400番台エラーがでた!
postリクエストをさせるにはまず認証を通過させる必要があるということ!

使い方は簡単

例として、モデルファクトリでユーザーを生成し、actingAsヘルパメソッドにそれを引数で渡してあげるだけで認証状態をつくれる!


        $user = factory(\App\Model\User::class)->create();// ユーザーのモックをつくって
        $response = $this->actingAs($user) //actingAs($user)とかくだけでユーザーがログインした状態にできる
            ->post("/api/survey/answer/complete",
                [
                   //post対象カラム
                 ]);

以上です!

参考記事:https://readouble.com/laravel/6.x/ja/http-tests.html

1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?