Skip to content

Instantly share code, notes, and snippets.

@sileence
Created August 22, 2019 09:01
Show Gist options
  • Save sileence/2c992f82f87127f540e729d7c2b1121a to your computer and use it in GitHub Desktop.
Save sileence/2c992f82f87127f540e729d7c2b1121a to your computer and use it in GitHub Desktop.
Example of validation test with Laravel using custom assertion to avoid code repetition
<?php
//......
class CreatePageTest extends TestCase
//.....
/** @test */
function meta_description_is_required()
{
$this->assertAdminCannotCreatePageWithout('meta_description');
}
protected function assertAdminCannotCreatePageWithout($field)
{
$this->assertAdminCannotCreatePageWith([$field => null]);
}
protected function assertAdminCannotCreatePageWith(array $invalidFields, array $additionalData = [])
{
$this->handleValidationExceptions();
$this->actingAs($this->anAdmin())
->post('admin/pages', $this->withData($invalidFields, $additionalData))
->assertSessionHasErrors(array_keys($invalidFields));
$this->assertDatabaseEmpty('pages');
}
protected function withData(array $custom = [], array $additional = [])
{
return array_merge($this->defaultData(), $custom, $additional);
}
protected function defaultData()
{
return $this->defaultData;
}
}
@sileence
Copy link
Author

sileence commented Aug 22, 2019

This is based on an idea @clemir had while working together on a project. I tweaked the code and added a few extras.

Usage:

For required fields:

$this->assertAdminCannotCreatePageWithout($requiredFieldHere);

For other types of validation:

$this->assertAdminCannotCreatePageWith([$invalidField => $invalidData]);

To test validations that depends on other (valid) fields:

$this->assertAdminCannotCreatePageWith([$invalidField => $invalidData], ['valid field' => 'valid data']);

(The above is useful when testing rules that depend on other fields like requiredIf).

Of course you need to adapt assertAdminCannotCreatePageWith depending on the action and module you are testing, the convention I use is:

assert[ROLE_HERE]Cannot[ACTION_VERB][MODULE_NAME][With|Without]

  • Overwrite the default method or set the default property in order to set the default fields.
  • Test that the table is empty or has not been changed at the end.
  • anAdmin is just a helper that returns an admin user created with a model factory.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment