Mohammed Manssour

Tags:PHP, Laravel
Laravel FormRequest Tester Package

A Simple collection of test helpers that help testing form request the easy way.

Why Bother

for full story on why this package was built please refer to This Blog Post

Installation

  • using composer
composer require --dev mohammedmanssour/form-request-tester
  • Add MohammedManssour\FormRequestTester\TestsFormRequests trait to your tests
Class CreateProjectRequestTest {
    use TestsFormRequests;
}

Testing a form request

you need to initialize the form request using formRequest method. It takes the FormRequest class as first argument. You can pass array data to be validated via post or put functions.

$this->formRequest(CreateProjectRequest::class)
    ->post([
        'title' => 'Laravel FormRequest Tester'
    ]);

the previous code will initialize the request with post method and/fake-route . if you want to change these options you can via the options array that can be set as a third argument

$this->formRequest(UpdatePost::class)
->put([
    'title' => 'New Title',
    'content' => 'Some Content here'
])
->withRoute('posts/{post}')
->withRouteParameter('post', 1)

After that use the available assertions to test for the incoming request.

Available Assertions

  • assertValidationPassed(): To make sure the validation have passed successfully with the help of the provided data
  • assertValidationFailed(): To make sure the validation have failed with the help of the provided data
  • assertValidationErrors($keys): To assert that the keys mentioned in the $keys have occurred in the errors bag.
  • assertValidationErrorsMissing($keys): To assert that the keys mentioned in the $keysArray have not occurred in the errors bag.
  • assertValidationMessages($messages) : To assert that the messages exists in the error bag. Used when you define custom messages for your validation.
  • assertAuthorized() : To assert that request have not been authorized via the form request.
  • assertNotAuthorized() : To assert that request have not been authorized via the form request.
  • assertValidationData($keys): To assert that the keys mentioned in the $keys have occurred in the validated data
  • assertValidationDataMissing($keys) : To assert that the keys mentioned in the $keysArray have not occurred in the validated data.

Example Usage

Taking into considerations

  1. title & content are required fields.
  2. Content field is required is a custom error message used for content field.
  3. `$this->route` method is used in authorize the request against a specific model.
  4. Route::put('posts/{post}', 'PostsController@update')is the route used to update a post.
$this->formRequest(UpdatePost::class)
->put([
    'title' => 'New Title'
])
->withRoute(`posts/{post}`)
->withRouteParameter('post', 1)
->assertAuthorized()
->assertValidationFailed()
->assertValidationErrors(['content'])
->assertValidationErrorsMissing(['title'])
->assertValidationMessages(['Content field is required'])