LoginSignup
2
3

More than 3 years have passed since last update.

[Laravel]単体テストでログインできない!

Last updated at Posted at 2019-07-11

LoginControllerでオーバーライドしたauthenticated()のテストをしていました。

Controllers/Auth/LoginController.php
/**
 * @param \Illuminate\Http\Request $request
 * @param mixed $user
 * @return \Illuminate\Http\Response
 */
protected function authenticated(Request $request, $user)
{
    return redirect('users/' . $user->id)->with('my_status', __('You logged in.'));
}

ログインに成功するとユーザーページにリダイレクトして
You logged in.というフラッシュメッセージを表示します。

テストのコード

/tests/Unit/LoginControllerTest.php
/**
 * A basic unit test example.
 *
 * @return void
 */
public function testAuthenticated()
{
    $user = factory(User::class)->create([
        'password' => '1234'
    ]);

    $response = $this->post('login', [
        '_token' => csrf_token(),
        'email' => $user->email,
        'password' => '1234',
        'remember' => 'on'
    ]);

    $response->assertRedirect('users/' . $user->id);
    $this->assertAuthenticatedAs($user);
}

テストを実行

$ vendor/bin/phpunit --filter='LoginControllerTest'
PHPUnit 7.5.13 by Sebastian Bergmann and contributors.

F.                                                                  2 / 2 (100%)

Time: 2.85 seconds, Memory: 26.00 MB

There was 1 failure:

1) Tests\Unit\LoginControllerTest::testAuthenticated
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
-'http://localhost/users/1'
+'http://localhost'

/home/user/php/app/lara58/vendor/laravel/framework/src/Illuminate/Foundation/Testing/TestResponse.php:224
/home/user/php/app/lara58/vendor/laravel/framework/src/Illuminate/Foundation/Testing/TestResponse.php:169
/home/user/php/app/lara58/tests/Unit/LoginControllerTest.php:32

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

http://localhost/users/1にリダイレクトしていないのでログイン失敗です。

解決方法

/tests/Unit/LoginControllerTest.php
$user = factory(User::class)->create([
    'password' => bcrypt('1234')
]);
$ vendor/bin/phpunit --filter='LoginControllerTest'
PHPUnit 7.5.13 by Sebastian Bergmann and contributors.

..                                                                  2 / 2 (100%)

Time: 2.68 seconds, Memory: 26.00 MB

OK (2 tests, 7 assertions)

成功しました。

他のテストでactingAs()メソッドを使った時はbcrypt()を使わなくてもできたのですが、ログインする時はbcrypt()が必要なようです。

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