vendredi 26 février 2021

How can I get Auth::user() to return the user created using a factory in a test?

I am working with Laravel 8.25. I have a Service class that has the following method:

public function getUsersBusinessManagers()
{
    $user = Auth::user()->id;

    return $user->businessManagers;
}

My test for this method is:

public function testCorrectBusinessManagersRetrievedForUser()
    {
        $user = User::factory()
            ->hasAttached(
                BusinessManager::factory()->count(1),
                ['user_fb_bm_id' => 'test']
            )
            ->create();
    
        $businessManagerService = new BusinessManagerService();
        $usersBusinessManagers = $businessManagerService->getUsersBusinessManagers();


        $this->actingAs($user)->assertEquals($user->businessManagers()->first()->id, $usersBusinessManagers->first()->id);
}

When running the test, how can I get Auth:user() in my service class to return the user I create in my test? Currently Auth:user() is null when I run the test.

Appreciate any help or guidance.

Aucun commentaire:

Enregistrer un commentaire