2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

LaravelのFormRequestの単体テストのやり方

Posted at

ただバリデーションテストを書きたいだけだった

こんな感じでValidator取得すればいけるやろ〜


$formRequest = new FormRequest();

$v = $formRequest->getValidator();

$v->passes();

そこでValidatorを取得できそうなメソッドを探したが、すべてprotectedメソッドだったのであった...

こんなふうに書きました

public function test_FormRequest_validate()
{
    $data = [];

    $formRequest = new FormRequest();

    $v = \Validator::make(
        $data, $this->app->call([$formRequest, 'rules']),
        $formRequest->messages(), $formRequest->attributes()
    );

    $this->assertTrue($v->passes());
}

もとのFormRequestクラスの内部では↓こんなふうにValidatorを取得しています。

$factory->make(
    $this->validationData(), $this->container->call([$this, 'rules']),
    $this->messages(), $this->attributes()
);

app->call()とすることで、rules()でメソッドインジェクションをしていた場合でもDIしてくれます。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?