Skip to content

Instantly share code, notes, and snippets.

@adamwathan
Created December 1, 2017 23:55
Show Gist options
  • Save adamwathan/c1e10a0ec564e2cf4b4c91294f9886ab to your computer and use it in GitHub Desktop.
Save adamwathan/c1e10a0ec564e2cf4b4c91294f9886ab to your computer and use it in GitHub Desktop.
Unit Testing Custom Validation Rules
<?php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
class Uppercase implements Rule
{
public function passes($attribute, $value)
{
return strtoupper($value) === $value;
}
public function message()
{
return 'The :attribute must be uppercase.';
}
}
<?php
namespace Tests\Feature\Rules;
use Tests\TestCase;
use App\Rules\Uppercase;
use Illuminate\Foundation\Testing\RefreshDatabase;
class UppercaseTest extends TestCase
{
/** @test */
function uppercase_strings_pass()
{
$rule = new Uppercase;
$this->assertTrue($rule->passes('attribute', 'SHOULDPASS'));
}
/** @test */
function mixed_strings_fail()
{
$rule = new Uppercase;
$this->assertFalse($rule->passes('attribute', 'ShouldNotPass'));
}
}
@tamilarasana
Copy link

hi bro
i hava doubts how to implement unit testing in laravel 8

@Adrug
Copy link

Adrug commented Aug 8, 2024

Example for custom boolean validator

class Boolean implements ValidationRule
{
    /**
     * Run the validation rule.
     *
     * @param  \Closure(string): \Illuminate\Translation\PotentiallyTranslatedString  $fail
     */
    public function validate(string $attribute, mixed $value, Closure $fail): void
    {
        if (filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE) === null) {
            $fail(
                'The :attribute must be boolean type. Accepted values are: true, false, 1, 0, "true", "false", "1", "0", "yes", "no", "off", "on".'
            );
        }
    }
}

Test case with Pest

    it('should pass for boolean', function ($value) {
        $validator = new Validator(resolve('translator'), ['test_parameter' => $value], ['test_parameter' => new Boolean]);

        expect($validator->passes())->toBeTrue();
    })->with([
        true,
        false,
        1,
        0,
        'true',
        'false',
        '1',
        '0',
        'yes',
        'no',
        'off',
        'on',
        null // as no value is passed, it should be considered as boolean
    ]);

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