Created
August 22, 2019 09:01
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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:
For other types of validation:
To test validations that depends on other (valid) fields:
(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]
anAdmin
is just a helper that returns an admin user created with a model factory.