YakutD's avatar

Why I cant test assertResponseStatus via Pest?

Trying to test redirection to specific error page route but i get error in console. This is my test function ( i m using Pest):

test('redirect to 404 error page', function()
{
    $route404 = 'page/which/not/exsist';

    $this->get($route404)
        ->assertResponseStatus(302)
        ->assertRedirectedToRoute('error.page', ['httpStatusCode' => 404]);
        
});

But I get error: "Call to undefined method Illuminate\Http\RedirectResponse::assertRedirectedToRoute()"

0 likes
4 replies
OussamaMater's avatar

I think you are trying to achieve this?

it('redirect to a 404 error page', function () {
    $not_found = 'page/which/not/exsist';

    $this->get($not_found)
        ->assertStatus(404)
        ->assertSee('hello world');
});

If open up the dev tools, if a page is not found, the status code will be 404, the response body has the view, so if you want to check if your custom error page is being rendered, you can assert that you see a header or an string :)

Above I am testing my custom error page resources/views/errors/404.blade.php, which contains hello world and the test is passing as expected.

I swapped test with it as I feel it is more coinvent and readable, and you can see the docs is using that keyword as well

YakutD's avatar

@OussamaMater no I exactly need to assert redirect, bc i redirect all http exceptions to sprecific error page.

OussamaMater's avatar

@YakutD Ah okay, but just letting you know, that you can write less code, worry less about redirecting and handling errors, let Laravel do this, instead you create the specific error page by making a directory called errors in which you put all the error pages by the status code.

For example if you want to create a custom 404 pages, which I believe what you are trying to do, you would do it like so

errors/404.blade.php

Inside that page, put the custom 404 page, and now instead of Laravel's default page, it will be yours, same goes for all the other status code like 401, 403, 500, etc..

cwhite's avatar
cwhite
Best Answer
Level 19

Try using the Pest\Laravel\get function:

use function Pest\Laravel\get;

it('redirects to 404 error page', function()
{
    get('page/which/not/exsist')
        ->assertFound()
        ->assertRedirectToRoute('error.page', ['httpStatusCode' => 404]);
        
});

also, it's assertRedirectToRoute() not Redirected.

1 like

Please or to participate in this conversation.