Testing validation rules can become quite tiresome pretty quickly if you have to write each test manually. Luckily I’ve found a nice method that allows you to simplify your validation rule tests when using Laravel Livewire components. For this example we have a form that allows a user to update their profile information with a Livewire ProfileForm component.

In Livewire you can define validation rules by setting a rules array (shown below) and then validate using $this->validate(). In this example we are  binding to a User model that has a name, email and bio.

protected $rules = [
    'user.name' => 'required|max:200',
];

In our example we need to do something a bit more complicated so instead of using the rules array we are going to create a rules function instead, allowing us to use the Illuminate\Validation\Rule::class. Here are the rules we have set and the save() method that will validate the input.

// App\Http\Livewire\ProfileForm.php

use Illuminate\Validation\Rule;

protected function rules() 
{
    return [
        'user.id' => 'required',
        'user.name' => 'required|max:200',
        'user.email' => ['required', 'email', Rule::unique('users')->ignore($this->user->id)],
        'user.bio' => 'required|min:20|max:1000',
    ];
}

public function save()
{
    $this->validate();

    // Save the user data
    $this->user->save();
}

So how can we go about testing each of these rules? There are 8 different validation rules in this simple example, but you don’t want to have to write 8 separate tests for each rule. Instead, we can make use of a data provider to pass the data to be tested into the test, along with the expected validation rule.

#php #laravel #livewire #validation

Testing Validation Rules in A Laravel Livewire Component
4.40 GEEK