作成日:2025-04-11, 更新日:2025-04-11
ログインチェックが必要なページ(/dashboardなど)を表示
ログインチェックはざっくりと3種類
- Laravel標準のログイン (auth)のみでチェック
- Laravel標準のログイン (auth)ではなく、セッションだけでログインチェック
- 独自処理でチェック
Laravel標準のログイン (auth)のみでチェック: actingAs
$user = User::factory()->create(); // 新規作成したユーザーを取得
// $user = User::where('email', 'hoge@example.test')->first(); // 既存ユーザーを使う
$this->actingAs($user); // ログイン処理実行
$response = $this->get('/dashboard'); // ダッシュボードを表示
Laravel標準のログイン (auth)ではなく、セッションだけでログインチェック: セッションをセット
$this->withSession([
'login_user_id' => 123,
'login_expire' => now()->addMinutes(30),
]);
$response = $this->get('/mypage/dashboard');
※laravel テストでのセッション withSession()、Session::put()
独自処理でチェック
ログインを実行してから必要なページをテスト
$data = array(
'memberid' => 'user@example.com',
'password' => 'secret',
'_token' => csrf_token(),
);
$response = $this->post(route('login'), $data);
// ログイン成功したか確認
$response->assertRedirect(route('dashboard'));
// 対象ページを表示して、表示されるか確認
$response = $this->get(route('dashboard'));
$response->assertStatus(200); // 表示されるか確認
$response->assertSee('ようこそ'); // 表示されたページに特定の文字があるか確認(任意)
※ログイン失敗していたら「$response->assertRedirect(route('dashboard'));」で止まってくれる
ログイン処理だけメソッドを分ける
あちこちのページで必要なのでメソッド化しておく
class LoginControllerTest extends TestCase
{
protected function loginAsTestUser(array $credentials = [])
{
$default = [
'memberid' => 'user@example.com',
'password' => 'secret',
'_token' => csrf_token(),
];
$data = array_merge($default, $credentials);
$response = $this->post(route('login'), $data);
$response->assertRedirect(route('dashboard')); // ログイン成功したか確認
return $response; // 必要であればレスポンスを返す
}
public function test_view_dashboard()
{
$this->loginAsTestUser(); // ログイン処理実行
$response = $this->get(route('dashboard'));
$response->assertStatus(200);
$response->assertSee('ようこそ');
}
public function test_view_settings()
{
$this->loginAsTestUser(); // ログイン処理実行
$response = $this->get(route('settings'));
$response->assertStatus(200);
}
}