Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel5 Unit Testing a Login Form

I ran the following test and I am receiving a failed_asserting that false is true. Can someone further explain why this could be?

/** @test */
public function a_user_logs_in()
{
    $user =  factory(App\User::class)->create(['email' => '[email protected]', 'password' => bcrypt('testpass123')]);

    $this->visit(route('login'));
    $this->type($user->email, 'email');
    $this->type($user->password, 'password');
    $this->press('Login');
    $this->assertTrue(Auth::check());
    $this->seePageIs(route('dashboard'));
}
like image 780
user3732216 Avatar asked Mar 13 '23 15:03

user3732216


2 Answers

Your PHPUnit test is a client, not the web application itself. Therefore Auth::check() shouldn't return true. Instead, you could check that you are on the right page after pressing the button and that you see some kind of confirmation text:

    /** @test */
    public function a_user_can_log_in()
    {
        $user = factory(App\User::class)->create([
             'email' => '[email protected]', 
             'password' => bcrypt('testpass123')
        ]);

        $this->visit(route('login'))
            ->type($user->email, 'email')
            ->type('testpass123', 'password')
            ->press('Login')
            ->see('Successfully logged in')
            ->onPage('/dashboard');
    }

I believe this is how most developers would do it. Even if Auth::check() worked – it would only mean a session variable is created, you would still have to test that you are properly redirected to the right page, etc.

like image 183
Denis Mysenko Avatar answered Mar 27 '23 16:03

Denis Mysenko


In your test you can use your Model to get the user, and you can use ->be($user) so that it will get Authenticate.

So i written in my test case for API test

    $user = new User(['name' => 'peak']);
    $this->be($user)
         ->get('/api/v1/getManufacturer')
          ->seeJson([
             'status' => true,
         ]);

it works for me

like image 44
Narayana Reddy Gurrala Avatar answered Mar 27 '23 15:03

Narayana Reddy Gurrala