はじめに
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 全体を、より実態に近くテストできる