I recently started implementing the unit testing in Laravel 9.x framework. So far, I was able to write some basic rules without any complications. However, in my application I am validating the forms using ajax and From Request for validation rules.
CategoryRequest.php
class CategoryRequest extends FormRequest
{
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
// ...
'title' => [
'required',
'max:255',
function($attributes, $value, $fails) {
$Category = Category::where([
'user_id' => request()->user_id,
'title' => request()->title,
])->first();
if($Category) {
$fails('`Category` is already taken');
}
}
],
// ...
];
}
}
CategoryTest.php
class CategoryTest extends TestCase
{
use RefreshDatabase;
// ...
public function test_new_category_with_unique_validation()
{
$user = $this->__user();
$arrayPost = [
'user_id' => $user->id,
'uuid' => Str::uuid(),
'title' => 'title',
'status' => STATUS['active'],
];
Category::factory()->create($arrayPost);
$response = $this
->actingAs($user)
->post('/console/categories', $arrayPost);
$response->assertJsonValidationErrorFor('title');
$response->assertJsonValidationErrorFor('status');
$response->assertJsonValidationErrorFor('uuid');
$response->assertJsonValidationErrorFor('user_id');
}
private function __user(): object
{
return User::factory()->create();
}
}
I am getting the following error...
What am I doing wrong?

$this->withExceptionHandling();in your test method.