Skip to content

Instantly share code, notes, and snippets.

@Lelectrolux
Last active October 15, 2020 16:55
Show Gist options
  • Save Lelectrolux/4ccef4a223dd51d5ed75d22adc9e9ea7 to your computer and use it in GitHub Desktop.
Save Lelectrolux/4ccef4a223dd51d5ed75d22adc9e9ea7 to your computer and use it in GitHub Desktop.
Testing forms validation errors in laravel
<?php
namespace Tests\Feature;
use App\Models\Model;
use Generator;
use Illuminate\Foundation\Testing\RefreshDatabase;
// use Illuminate\Support\Facades\Mail;
use Tests\TestCase;
class FormTest extend TestCase
{
use RefreshDatabase;
/**
* @test
* @dataProvider providesErrorCases
*/
public function validation_errors(array $invalidData, array $errorMessages): void
{
// Mail::fake();
// Other side effects setup
$response = $this->from('/previous')
->post('/url', array_merge([
'field' => 'Foo',
'other-field' => 'Bar',
], $invalidData));
$this->assertFalse(Model::query()->exists(), 'No Model should be saved to the database');
// Mail::assertNothingQueued();
// Mail::assertNothingSent();
// Other side effect assertions
$response->assertRedirect('/previous')
->assertSessionHasErrors($errorMessages);
}
public function providesErrorCases(): Generator
{
// If php > 7.4 : remove call to create application and use short closure to delay calls to __() function
$this->createApplication();
yield from [
'field_is_required' => [
['field' => ''],
['field' => __('validation.required', ['attribute' => __('validation.attributes.field')])],
],
'field_is_255_character_max' => [
['field' => str_repeat('a', 255 + 1)],
['field' => __('validation.max.string', ['attribute' => __('validation.attributes.field'), 'max' => '255'])],
],
];
yield from [
'other-field_is_required' => [
['other-field' => ''],
['other-field' => __('validation.required', ['attribute' => __('validation.attributes.other-field')])],
],
'field_is_255_character_max' => [
['other-field' => str_repeat('a', 255 + 1)],
['other-field' => __('validation.max.string', ['attribute' => __('validation.attributes.other-field'), 'max' => '255'])],
],
];
// Or even
yield from require __DIR__.'/common-validations/thrid-field.php';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment