Laravel 7 Unit Test to registration route redirects to home page

Viewed 631

I am using an almost entirely out of the box registration process that Laravel 7 provides.

When I try and submit an invalid registration form via the form in a web browser, I get returned to the registration page with a list of errors which is what I am expecting to happen.

However, I am trying to write a unit test for this functionality but for some reason, when I make the same request in a unit test I get a response to redirect to root page /.

Why does my unit test not return the same HTML response as when I make the same request through the browser? I suspected it might be due to the lack of a CSRF token being sent in the request, but according to the documentation, CSRF middle-ware is supposed to be disabled during unit tests.

The CSRF middleware is automatically disabled when running tests.

Here's my unit test code:

public function testPostInvalidRegistration(){

    $response = $this->post("/register",[
        'first_name' => $this->faker->name
    ]);
    
    $response->dumpSession();
    $response->dump();
    $response->dumpHeaders();

}

And here is the output of $response->dump()

<!DOCTYPE html>\n
<html>\n
    <head>\n
        <meta charset="UTF-8" />\n
        <meta http-equiv="refresh" content="0;url='http://localhost'" />\n
\n
        <title>Redirecting to http://localhost</title>\n
    </head>\n
    <body>\n
        Redirecting to <a href="http://localhost">http://localhost</a>.\n
    </body>\n
</html>

In $response->dumpSession() I can see that the validator ran and has the errors listed.

1 Answers

This is the way laravel works. When the form validation fails, you will be redirected to the previous location. Since there is just one request in your test, there is no previous location. The fallback is to redirect to /.

For the behaviour you want, you have to set the referer header to the path of your registration form page. To get the rendered response of your form, you have to follow the redirect.

    public function testPostInvalidRegistration()
    {
        $this->followingRedirects();

        $response = $this->post(
            "/register",
            [
                'first_name' => $this->faker->name
            ],
            ['Referer' => '/registration-form']
        );

        // Assert stuff
    }
Related