0

I created a simple custom validation rule via php artisan make:rule, and now I want to write unit tests for it.

How do I test a validation rule to pass or fail?

Since $rule->validate() does not return nor throw anything how can I assert that it failed or not in my test?

1 Answer 1

1

If we are directly testing a rule as a unit, the best way to approach this would be to manually create a validator with your supplied data and test if that given validator passes. For this instance, we can create a simple rule that passes if the value is true:

TestRule.php

public function validate(string $attribute, mixed $value, Closure $fail): void
{
    if ($value === true) {
        return;
    }

    $fail('The validation failed.');
}

Then, within your test, create a new validator instance for some attribute and apply your rule to it:

/** @test */
public function it_will_pass_if_supplied_with_a_true_value(): void
{
    $data = ['test' => true];

    $validator = Validator::make($data, ['test' => new TestRule()]);

    $this->assertTrue($validator->passes());
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.