LoginSignup
7
7

More than 3 years have passed since last update.

laravel お手軽WebAPIテスト 認証無視or認証(ミドルウェア無視)

Last updated at Posted at 2019-04-20

◆Laravel認証機能利用

コマンド
php artisan make:auth
php artisan migrate

usersとpassword_resetsテーブルが作成される。
ユーザー登録画面にアクセスしてユーザーを作成する。

名前:test
email:test\@test.co.jp
Password:Test1234

ユーザー作成完了

HomeContoroller
class HomeController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function index()
    {
        return view('home');
    }
}

HomeControllerを見ると、__constructの中でmiddlewareのauthを呼んでいます。
これで、認証していないユーザーはhome画面を返すメソッドが実行される前に、はじかれるため閲覧できません。

◆テスト実装の前に

テストを実装していく前にわかりやすいように、適当なルートとメソッドを作成します。

web.php
Route::get('/sample', 'HomeController@sample')->name('sample');
HomeController
class HomeController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function index()
    {
        return view('home');
    }

    public function sample()
    {
        return '認証成功';
    }
}

認証されているユーザーが/sampleにアクセスした場合、「認証成功」文字列を返すようにしました。

◆テストを実装していく

ExampleTest
class ExampleTest extends TestCase
{
    public function testSample()
    {
        $response = $this->get('/sample');

        $response->assertStatus(200);
    }
}
コマンド
root@419602892fb6:/var/www# vendor/bin/phpunit tests/Feature/ExampleTest.php
PHPUnit 7.5.8 by Sebastian Bergmann and contributors.

F                                                                   1 / 1 (100%)

Time: 1.47 seconds, Memory: 16.00 MB

There was 1 failure:

1) Tests\Feature\ExampleTest::sample
Expected status code 200 but received 302.
Failed asserting that false is true.

/var/www/vendor/laravel/framework/src/Illuminate/Foundation/Testing/TestResponse.php:133
/var/www/tests/Feature/ExampleTest.php:17

FAILURES!
Tests: 1, Assertions: 1, Failures: 1.

テストが通るか試すと、ログインしていないので、テストがうまくいきません。

◆ミドルウェア無視する

ExampleTest
class ExampleTest extends TestCase
{
    public function testSample()
    {
        $response = $this->withoutMiddleware()->get('/sample');

        $response->assertStatus(200);
    }
}

テスト成功
withoutMiddlewareは引数を指定すると特定のミドルウェアを無視して、指定しないとすべてのミドルウェアを無視します

◆ActingAsメソッドで認証ユーザー設定

class ExampleTest extends TestCase
{
    public function testSample()
    {
        $user = factory(User::class)->create([
            'password' => bcrypt('Test1234')
        ]);

        $response = $this->actingAs($user)->get('/sample');

        $response->assertStatus(200);
    }
}

テスト成功。テストする先で認証ユーザー情報を使うときに使えそう。
ミドルウェアを無視した場合でも、これを使えば認証ユーザー情報を使えます。

◆ログインさせてからテスト

ExampleTest
class ExampleTest extends TestCase
{
    public function testSample()
    {
        $this->post('/login', [
            'email'    => 'test\@test.co.jp',
            'password' => 'Test1234'
        ]);

        $response = $this->get('/sample');

        $response->assertStatus(200);
    }
}

テスト成功

◆fackerでユーザー作成してログインしてテスト

ExampleTest
class ExampleTest extends TestCase
{
    public function testSample()
    {
        $user = factory(User::class)->create([
            'password' => bcrypt('Test1234')
        ]);

        $this->post('/login', [
            'email'    => $user->email,
            'password' => 'Test1234'
        ]);

        $response = $this->get('/sample');

        $response->assertStatus(200);
    }
}

テスト成功
パスワードだけHashの影響があるために変えております。

まとめ

シナリオテストのときとかfackerユーザー作成利用してやってみたいと感じた。

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