XiaTesting's avatar

Test FormRequest class.

I create a Form request class as StoreCategoryRequest that function authorizes return true, and function rules have required a title.

class StoreCategoryRequest extends FormRequest { public function authorize() { return true; }

public function rules()
{
    return [
        'title' => 'required|unique:categories|max:255',
    ];
}

public function messages()
{
    return [
        'title.required' => 'A title is required for category',
    ];
}

}

and In my controller :

public function store(StoreCategoryRequest $request)
{
    
    Category::create($request->validated());

}

In my test I have public function test_if_can_hit_create_category_end_point() {

    $responseStatus = 200;

    $response = $this->post('/category', [
        'title' => 'Event',
    ]);

    $response->assertStatus(200);

}

public function test_if_can_create_category()
{

    $responseStatus = 201;

    $response = $this->post('/category', [
        'title' => 'Event',
    ]);

    $this->assertCount(1, Category::all());

} 

public function test_a_title_field_is_required()
{

    $response = $this->post('/category', [
        'title' => '',
    ]);

    $response->assertSessionHasErrors('title');

}

, I changed Request $request to StoreCategoryRequest $request then started to fail all test, before that, all works fine.

Any help. Thanks-.

0 likes
1 reply
XiaTesting's avatar

The first test now shows:

Expected status code 200 but received 500. Failed asserting that 200 is identical to 500.

The 2nd :

Failed asserting that actual size 0 matches expected size 1.

The 3rd:

Failed asserting that false is true.

Please or to participate in this conversation.