0
1

LaravelのFeatureテストでうまくいかない時に試してみること

Last updated at Posted at 2024-07-25

例外が出ていないか確認コードを入れてみる

魔法の三行
if ($response->exception) {
    dd($response->exception);
}

Controllerのメソッドをテストするためにリクエストを投げても、そのメソッドにそもそも辿り着いていなさそうなエラーが出ている時があった。
具体的には、会員登録ページの「登録ボタンの遷移」テストをしているときに、意図している仮登録完了後のページに遷移していなかったのだ。

public function test_登録処理テスト_バリデーション()
{
    $name = FakerFactory::create()->unique()->regexify('[A-Za-z0-9]{10}');
    $request = new Request([
        'name' => $name,
        'email' => FakerFactory::create()->unique()->email(),
        'password' => FakerFactory::create()->password(),
        ...
    ]);

    $response = $this->post('/register', $request->toArray());
    $response->assertStatus(302);
    $response->assertRedirect('/auth/pre_complete'); // ここでエラーが発生

    // データベースにユーザーが登録されたことを確認
    $this->assertDatabaseHas('users', [
        'name' => $name,
    ]);
}
出力
❌ 登録処理テスト_バリデーション 910 ms
 ┐ 
 ├ Failed asserting that two strings are equal.
 ┊ ---·Expected 'https://xxx/auth/pre_complete'
 ┊ +++·Actual 'https://xxx'

しかしエラーらしきものは出ていないし、トップに飛ぶようなリダイレクト処理も出ていない。
そんな時はリクエストを投げた直後くらいに上の3行を挟んでみると、以下のような隠れエラーが出てきた。

Illuminate\Session\TokenMismatchException {#1032
  #message: "CSRF token mismatch."

どうやらCSRFトークンエラーが出ていたようだ。
POST時にCSRFトークンチェックを外すようにして解決。

ReCaptchaのテストを飛ばしたい

以下の二つを .env.testing に追加する。

.env
NOCAPTCHA_SITEKEY=6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI
NOCAPTCHA_SECRET=6LeIxAcTAAAAAGG-vFI1TnRWxMZNFuojJ4WifJWe
config/no-captcha.php
<?php

return [
    'secret'  => env('NOCAPTCHA_SECRET', 'no-captcha-secret'),
    'sitekey' => env('NOCAPTCHA_SITEKEY', 'no-captcha-sitekey'),
]

参考文献

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