How to test form request rules in Laravel 5? How to test form request rules in Laravel 5? laravel laravel

How to test form request rules in Laravel 5?


The accepted answer tests both authorization and validation simultaneously. If you want to test these function separately then you can do this:

test rules():

$attributes = ['aa' => 'asd'];$request = new MyRequest();$rules = $request->rules();$validator = Validator::make($attributes, $rules);$fails = $validator->fails();$this->assertEquals(false, $fails);

test authorize():

$user = factory(User::class)->create();$this->actingAs($user);$request = new MyRequest();$request->setContainer($this->app);$attributes = ['aa' => 'asd'];$request->initialize([], $attributes);$this->app->instance('request', $request);$authorized = $request->authorize();$this->assertEquals(true, $authorized);

You should create some helper methods in base class to keep the tests DRY.


You need to have your form request class in the controller function, for example

public function store(MyRequest $request)

Now create HTML form and try to fill it with different values. If validation fails then you will get messages in session, if it succeeds then you get into the controller function.

When Unit testing then call the url and add the values for testing as array. Laravel doc says it can be done as

$response = $this->call($method, $uri, $parameters, $cookies, $files, $server, $content);


Here's a full example of testing validation:

use App\Http\Requests\PostRequest;use Illuminate\Routing\Redirector;use Illuminate\Validation\ValidationException;class PostRequestTest extends TestCase{    protected function newTestRequest($data = [])    {        $request = new PostRequest();        $request->initialize($data);        return $request            ->setContainer($this->app)            ->setRedirector($this->app->make(Redirector::class));    }    public function testValidationFailsWhenEmptyTitleIsGiven()    {        $this->expectException(ValidationException::class);        $this->newTestRequest(['title' => ''])->validateWhenResolved();    }}