Skip to content

Instantly share code, notes, and snippets.

@egulhan
Last active June 30, 2021 08:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save egulhan/eb46f80ac520029872f9b94c6ae06827 to your computer and use it in GitHub Desktop.
Save egulhan/eb46f80ac520029872f9b94c6ae06827 to your computer and use it in GitHub Desktop.
Test validations of a FormRequest in Laravel
<?php
namespace Tests\Unit;
use Tests\TestCase;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use App\Models\Notification\PushNotification;
use App\Modules\Partner\Requests\CreatePushNotificationRequest;
class PushNotificationTest extends TestCase
{
/** @test */
public function it_should_get_validation_error_by_not_entering_email_address_while_sending_push_notification()
{
$data = [
'push_notification_service_provider_id' => $this->faker->numberBetween(1, 100),
// 2: email
'target_type_id' => 2,
'target_value' => $this->faker->word,
'title' => $this->faker->word,
'message' => $this->faker->word,
'send_now' => 1,
'status' => 1,
];
$request = new CreatePushNotificationRequest();
$rules = $request->rules();
$validator = \Validator::make($data, $rules);
// fails() check must be before withValidator() validation
$fails = $validator->fails();
// trigger manually withValidator after
$validator->after($request->withValidatorAfter($validator));
$messages = $validator->messages()->messages();
$this->assertFalse($fails);
$this->assertTrue(array_key_exists('target_value', $messages));
}
}
?>
@ianjamieson
Copy link

My current version of Laravel, 8.0. I needed to change:

$validator->after($request->withValidatorAfter($validator));

To:

$validator->after([$request, 'withValidatorAfter']);

As after was expecting a callable

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