LoginSignup
24
23

More than 3 years have passed since last update.

Laravelで認証用APIのテストを書く

Last updated at Posted at 2019-04-17

Laravel + Vue.jsを勉強している際に、APIを利用した認証でログアウトを確認するためのUnitテストで、便利なアサーションがあったので、備忘録として記録

前提

  • Laravel5.8(5.5~)

テストケースの作成

Laravelのドキュメントルート上で、以下コマンドを実行する

php artisan make:test AuthenticationTest

テストコード

tests/Feature/AuthenticationTest.php
<?php

namespace Tests\Feature;

use App\User;

use Tests\TestCase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\RefreshDatabase;

class AuthenticationTest extends TestCase
{
    use RefreshDatabase;

    protected $user;

    public function setUp(): void
    {
        parent::setUp();

        // テストユーザ作成
        $this->user = factory(User::class)->create();
    }

    /**
     * ログイン認証テスト
     */
    public function testLogin(): void
    {
        // 作成したテストユーザのemailとpasswordで認証リクエスト
        $response = $this->json('POST', route('login'), [
            'email' => $this->user->email,
            'password' => 'password',
        ]);

        // 正しいレスポンスが返り、ユーザ名が取得できることを確認
        $response
            ->assertStatus(200)
            ->assertJson(['name' => $this->user->name]);

        // 指定したユーザーが認証されていることを確認
        $this->assertAuthenticatedAs($this->user);
    }

    /**
     * ログアウトテスト
     */
    public function testLogout(): void
    {
        // actingAsヘルパで現在認証済みのユーザーを指定する
        $response = $this->actingAs($this->user);

        // ログアウトページへリクエストを送信
        $response->json('POST', route('logout'));

        // ログアウト後のレスポンスで、HTTPステータスコードが正常であることを確認
        $response->assertStatus(200);

        // ユーザーが認証されていないことを確認
        $this->assertGuest();
    }
}

注目すべきは、ヘルパメソッドの使い勝手の良さ。

actingAs()は、現在認証済みのユーザーを容易に設定することができる。
assertGuest()は、認証状態でないことを簡単に確認することができる。

参考サイト

24
23
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
24
23