Skip to content

Instantly share code, notes, and snippets.

@agm1984
Last active July 10, 2020 03:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save agm1984/d571f8095881d14c47d12f492af5b85d to your computer and use it in GitHub Desktop.
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
<?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