Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Failing authentication test, using Laravel, phpunit and Homestead

So, I'm trying to test the register and login features on a Laravel 5.8 project, running on Homestead.

My problem is that I can't get the tests (for login and for register) to pass the assertAuthenticated() and assertAuthenticatedAs() functions.

I created the login feature using php artisan make:auth and didn't changed a lot, just created a "username" field to use instead of email.

When I test things like assertStatus(), $this->get(url), everything works fine but when I add the line $this->assertAuthenticatedAs($user) for example, the test crashes.

This is my actual passing function:

    public function test_login_valid_user()
    {
        $user = factory(User::class)->create();

        $response = $this->post('/login', [
            'username' => $user->username,
            'password' => 'secret'
        ]);

        $response->assertStatus(302);

    }

If I add the line $this->assertAuthenticatedAs($user) at the end, I get the following error:

There was 1 failure:

1) Tests\Feature\Auth\LoginTest::test_login_valid_user
The current user is not authenticated.
Failed asserting that null is not null.

/home/vagrant/code/my_project/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithAuthentication.php:89
/home/vagrant/code/my_project/tests/Feature/Auth/LoginTest.php:39

The same is happening on my register test, after the user is registered, when I try to check $this->assertAuthenticated() I get the same error.

So, I thought about session problems related to Vagrant/Homestead, but I just started to use them and couldn't find any hint about it. And I'm very new to PHPUnit and testing in general, I'm just starting to understand how it works.

like image 647
BarbaAlGhul Avatar asked Apr 20 '19 22:04

BarbaAlGhul


1 Answers

The problem is connected with caches.

First of all file phpunit.xml must be read because you need: <server name="APP_ENV" value="testing"/>

Before your tests use command

 php artisan config:clear

After that your dump(config('app.env')); will be testing (not local).

Then all works.

like image 190
Adam Kozlowski Avatar answered Nov 15 '22 12:11

Adam Kozlowski