LoginSignup
3
3

More than 3 years have passed since last update.

LaravelのFormRequestのテストをちゃんと書く

Posted at

はじめに

以前にLaravelのFormRequestの単体テストのやり方という記事を書きましたが、この方法だとprepareForValidation()passedValidation()のメソッドは使われないので、これらのメソッドに処理を記述している場合はテストができないということになります。

なので、これらのメソッドも実行されるようなFormRequestのテストの書き方を書いていきます。

テストする

そもそもprepareForValidation()passedValidation()はprotectedなのでメソッド単位でテストすることができないので、FormRequest全体の流れをテストします。

public function test_()
{
    $parameters = ['key' => 'value'];

    $request = Request::create('', 'GET', $parameters);
    app()->instance('request', $request);
    $formRequest = app(HogeFormRequest::class);

    $this->assertSame('value2', $formRequest->get('key'));
}

$parametersに実際送信するパラメーターを連想配列で記述してください。

注意点はapp(HogeFormRequest::class);で解決した時点でバリデーションを含む一連の処理が完了してます。

3
3
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
3
3