Unit Test Laravel’s FormRequest

I found a good solution on Laracast and added some customization to the mix.

The Code

/**
 * Test first_name validation rules
 * 
 * @return void
 */
public function test_valid_first_name()
{
    $this->assertTrue($this->validateField('first_name', 'jon'));
    $this->assertTrue($this->validateField('first_name', 'jo'));
    $this->assertFalse($this->validateField('first_name', 'j'));
    $this->assertFalse($this->validateField('first_name', ''));
    $this->assertFalse($this->validateField('first_name', '1'));
    $this->assertFalse($this->validateField('first_name', 'jon1'));
}

/**
 * Check a field and value against validation rule
 * 
 * @param string $field
 * @param mixed $value
 * @return bool
 */
protected function validateField(string $field, $value): bool
{
    return $this->validator->make(
        [$field => $value],
        [$field => $this->rules[$field]]
    )->passes();
}

/**
 * Set up operations
 * 
 * @return void
 */
public function setUp(): void
{
    parent::setUp();

    $this->rules     = (new UserStoreRequest())->rules();
    $this->validator = $this->app['validator'];
}

Update

There is an e2e approach to the same problem. You can POST the data to be checked to the route in question and then see if the response contains session errors.

$response = $this->json('POST', 
    '/route_in_question', 
    ['first_name' => 'S']
);
$response->assertSessionHasErrors(['first_name']);

Leave a Comment