6
votes

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.

2

2 Answers

8
votes

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.

1
votes

I'd been experiencing same problem. For unit tests CSRF token verification should be disabled, but only if you are running under APP_ENV=testing. I though phpunit.xml was overriding my "local" config so it was set to "testing". It was not, because PhpStorm was not reading this file.

If you are using PHPStorm don't forget to check path to default config file - phpunit.xml. (Settings -> Languages&Frameworks -> PHP -> Test frameworks)