AngelGris
1319
4
Testing

Phpunit testing form validation

Posted 1 year ago by AngelGris

I'm trying to write some tests for my forms in order to confirm the validators retrieve the expected errors when required. The form only has 3 fields: name, discount and expiration and the validator looks like this:

$this->validate($request, [
    'name'          => 'required',
    'discount'      => 'required|numeric|between:1,100',
    'expiration'    => 'required|date_format:d/m/Y',
]);

That works fine both when submitting the form and when running the tests with phpunit using the following code:

/**
 * Discount must be numeric check
 */
$response = $this->post(route('offer.create'), [
    'name'          => $faker->sentence(4),
    'discount'      => 'asdasd',
    'expiration'    => $faker->dateTimeBetween('+1 days', '+5 months')
]);

// Check errors returned
$response->assertSessionHasErrors(['discount']);

Since discount is not numeric it throws the expected error and everybody is happy.

Now, if I want to add a new rule to make sure that the expiration is equal or greater to today I add the after:yesterday rule leaving the validator like:

$this->validate($request, [
    'name'          => 'required',
    'discount'      => 'required|numeric|between:1,100',
    'expiration'    => 'required|date_format:d/m/Y|after:yesterday',
]);

That works fine when submitting the form, I get the error saying the discount is not numeric. But when testing with phpunit it doesn't get the error as expected:

1) Tests\Feature\CreateSpecialOfferTest::testCreateSpecialOffer
Session missing error: expiration
Failed asserting that false is true.

Why adding this new validation rule to expiration generates a false validation in discount? Is this a bug in the validator or am I missing something?

Also:

1 - is there a better way to test form validators?

2 - is there an assert that is the opposite of assertSessionHasErrors() to check a certain error is NOT been thrown?

Please sign in or create an account to participate in this conversation.