Last active
July 10, 2020 03:14
-
-
Save agm1984/d571f8095881d14c47d12f492af5b85d to your computer and use it in GitHub Desktop.
Demonstration of how to use a `resetAuth` function to fully reset auth state in-between Laravel unit tests. For theory, see: https://stackoverflow.com/a/57941133/6141025
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use Illuminate\Auth\SessionGuard; | |
// ... | |
/** | |
* Resets AuthManager state by logging-out the user from all auth guards. | |
* This is used between unit tests to wipe cached auth state. | |
* | |
* @param array $guards | |
* @return void | |
*/ | |
protected function resetAuth(array $guards = null) : void | |
{ | |
$guards = $guards ?: array_keys(config('auth.guards')); | |
foreach ($guards as $guard) { | |
$guard = $this->app['auth']->guard($guard); | |
// \Log::debug("logging out guard: {$guard}"); | |
if ($guard instanceof SessionGuard) { | |
$guard->logout(); | |
} | |
} | |
$protectedProperty = new \ReflectionProperty($this->app['auth'], 'guards'); | |
$protectedProperty->setAccessible(true); | |
$protectedProperty->setValue($this->app['auth'], []); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment