LoginSignup
5
0

More than 3 years have passed since last update.

Laravel の FormRequest を全体的に、実態に近く自動テストする

Posted at

はじめに

Laravel の FormRequest のテストの話は rules() のテストだけなのが多いので、rules() 以外も含む FormRequest 全体を、より実態に近くテストする話をする

テスト

以降は次を use する前提

use App\Http\Requests\HogeRequest;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;

全体なので FormRequest の passedValidation() や failedValidation() の実装の影響を受ける
以降はこれらがデフォルトの実装の前提。上書くときはその処理に従う。

成功することをテストする

FormRequest がサービスコンテナによる解決によって効果を得ることをテストする

public function testPass()
{
    $attributes = ['key' => 'value'];
    // FormRequest が依存する Request に入力値をセット
    $this->app->make(Request::class)->replace($attributes);
    // Controller で DI するのと同じ効果を得る
    $request = $this->app->make(HogeRequest::class);
    // risky になるので assert
    $this->assertInstanceOf(HogeRequest::class, $request);
}

失敗することをテストする

public function testFail()
{
    $attributes = ['key' => null];
    // FormRequest が依存する Request に入力値をセット
    $this->app->make(Request::class)->replace($attributes);
    // Controller で DI すると例外が投げられるのと同じ効果を得る
    $this->expectException(ValidationException::class);
    $this->app->make(HogeRequest::class);
}

おわりに

サービスコンテナによる解決によって、rules() 以外も含む FormRequest 全体を、より実態に近くテストできる

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