Feb 17, 2022
0
Level 4
Testing a middleware with Redis and timestamps
So I got a simple Middleware that's fired on every request to store a timestamp for authenticated users (last seen).
public function handle(Request $request, Closure $next)
{
if (! Auth::check()) {
return $next($request);
}
$key = 'last_seen_'.Auth::id();
$value = now()->format('Y-m-d H:i:s');
Redis::set($key, $value);
return $next($request);
}
And the test that fails randomly with a second off...
test('last seen is set', function () {
$user = User::factory()->create();
testTime()->freeze('2021-01-02 12:34:56');
\Illuminate\Support\Facades\Redis::shouldReceive('set')
->once()
->with('last_seen_'.$user->id, '2021-01-02 12:34:56');
$this
->actingAs($user)
->get('/');
});
The test time is frozen, however the time used in the middleware still moves forward making the test fail. Any ideas how this is tested properly?
Please or to participate in this conversation.