Home > Net >  How to unit test if the user is being redirected to login page if email not validated
How to unit test if the user is being redirected to login page if email not validated

Time:09-17

I'm trying to write some unit tests for my code, I'm just learning how to write tests and I'm new to Laravel. Basically, I have a simple project, where the user should register and after validating their email, they are redirected to the landing page. In order to avoid some infinite redirects and bugs, I added a few lines of code that prevents the user to redirect himself to the landing page before verifying their email. So this is what I have in the controller file :

public function index(): View|RedirectResponse
    {
        if (auth()->user()->email_verified_at)
        {
            return view('landing.country', [
                'countries'  => Countries::all(),
            ]);
        }

        auth()->logout();
        return redirect(route('home'));
    }

So, If the user hasn't verified his email, if he attempts to view the blade only accessible to authenticated users, I'm logging him out and redirecting to the login page. Even though writing this was quite simple, I'm having a hard time coming up with a proper way to test this. How should I be able to approach testing this particular logout section? I have to test if the user attempts to enter auth only blade and check if he is being logged out and redirected to input page? Any help would be appreciated, currently I've been trying something like this in my test units :

public function test_if_user_is_logged_out()
    {
        User::factory()->create();
        $user = User::first();
        Auth::logout();
        $response = $this->actingAs($user)->get(route('landing.worldwide'));
        $response->assertRedirect(route('home'));
    }

But obviously it doesn't work. I'd be forever thankful for any suggestions and help!

CodePudding user response:

You could update your test to something like:

public function test_an_unverified_user_is_logged_out_and_redirected()
{
    $user = User::factory()->unverified()->create();

    $this->actingAs($user)
        ->get(route('landing.worldwide'))
        ->assertRedirect(route('home'));

    $this->assertGuest();
}

unverified() is a method that is included with fresh installs of Laravel. If you don't have unverified() in your UserFactory, you can simply change the user create call to be:

$user = User::factory()->create([
    'email_verified_at' => null,
]);
  • Related