Skip to content

Instantly share code, notes, and snippets.

@agm1984
Last active Jul 10, 2020
Embed
What would you like to do?
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