ラボ > Laravel、Lumen:テスト

laravel テストでのセッション withSession()、Session::put()

セッションの取り扱い

作成日:2025-04-11, 更新日:2025-04-11

基本

getやpost時に1回だけ使うならwithSession()
保持するならSession::put()

// 省略
class HogeControllerTest extends TestCase {
  public function test_run_1st() {
    // 省略
    $response = $this->withSession([
      'ses_1st' => 789,
    ])->post(●●●●); // ← ses_1stは有効

    Session::put('ses_2nd', '123');
    $response = $this->post(●●●●); // ← ses_1stは無効、ses_2ndは有効

    $response = $this->withSession([
      'ses_3rd' => 456,
    ])->post(●●●●); // ← ses_1stは無効、ses_2nd、ses_3rdは有効

    $response = $this->post(●●●●); // ← ses_1stは無効、ses_2ndは有効、ses_3rdは無効

    // 省略
  }

  public function test_run_2nd() {
    // 省略

    echo Session::put('ses_2nd'); // test_run_1st()でセットしていても、ココではnullになるらしい

    // 省略
  }
}