ntraykov's avatar

How to test that a user is successfuly logged in?

I have the following test:



    /** @test */
    public function after_registration_the_user_must_be_logged_in()
    {
        $email = $this->faker->email;


        $response = $this->sendAjax('post', '/auth/register', [

            'email' => $email,

            'password' => $this->faker->password
            
        ]);


        $this->assertEquals($email, auth()->user()->email);
    }

It passes 3 or 4 times, but sometimes it fails. How to properly assert that the user is logged in?

This is an ajax request, so I'm not redirected to any page that is only for logged in users. That's why I want to test the session. Any clues?

0 likes
6 replies
Nash's avatar

Check your response. Are you certain that the user is successfully registered every time? It could be that the generated password does not adhere to the validation rules or that the email is not unique (if you are not using the RefreshDatabase trait)?

For this test, why not manually define the email and password, e.g. "[email protected]" and "testpassword1234"?

1 like
ntraykov's avatar

I am using RefreshDatabase. These are my validation rules:


request()->validate([

    'email' => 'required|email|max:255',

    'password' => 'required|min:8'

 ]);
            

I didn't put unique validation here, but this is not the problem because if I didn't put the RefreshDatabase trait, I would have a different error. Also, the error had to be every time, not once in 3-4 tests.

Nash's avatar

Does it work every time if you manually define the email and password instead of using faker?

1 like
ntraykov's avatar

It passes but I don't understand what happened?

Please or to participate in this conversation.