laravelvalidationlaravel-10laravel-validation

Laravel 10 custom validation rule testing


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?


Solution

  • 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());
    }