Summer Sale! All accounts are 50% off this week.

martinro's avatar

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?

0 likes
0 replies

Please or to participate in this conversation.