'loginAs() using different database for user sometimes works and sometimes fail

In the application I'm testing the user is being created or fetched from a different database connection. My problem is loginAs() seems like unstable with this setup and mostly it works but sometimes it failed to login the user I'm passing and the page I'm visiting is redirecting me to login page as if no one was logged in. Here's an example of how I visit a page using loginAs():

$user = User::find(1);
$this->browse(function (Browser $browser) use ($user) {
    $browser->loginAs($user)
        ->visit('/dashboard')
        ->waitForLocation('/dashboard')
        ->assertPathIs('/dashboard');
});

Sometimes the test failed for waiting for the location /dashboard because the page was being redirected to /login

I tried to print in the console the $user variable to see if it's null when the test failed but it is always has some data and yet the error still occurs. I also tried to add assertAuthenticatedAs($user) to see if what happens after loginAs() in my surprise there is no authenticated user with errors like this:

The currently authenticated user is not who was expected.
Failed asserting that null is identical to Array &0 (
    'id' => 1
    'className' => 'App\User'
)

So eventhough the $user is not null the loginAs() failed to login the user. (NOT ALL THE TIME)

Tried searching solution for this issue and I came across with this thread in github but looks like it's still unsolved.

Hope someone can give some inputs on how to solve this.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source