I have a unit test for caching an API key in redis (in a rails app).
redis is set to a global variable ($redis
) with the connection_pool
gem. So I do $redis.with do |redis|
to actually get the redis connection.
The issue is, my test is incredibly flaky. It has two assertions: one to test getting the expected value out and another to test that value is cached (for 10 minutes).
jwt = JWT.encode payload, private_key, "RS256"
assert_equal jwt, Foo.app_token
travel 5.minutes
assert_equal jwt, Foo.app_token
I can't work out why the test is so flaky. It fails maybe every 3-5 runs. Any help would be greatly appreciated. I've never really used redis inside a connection pool so may well be doing something basic wrong.
The implementation of the method:
def app_token
find_app_token || create_app_token
end
private
def find_app_token
$redis.with { |redis| redis.get APP_KEY }
end
def create_app_token
payload = # some payload
JWT.encode(payload, private_key, "RS256").tap do |jwt|
$redis.with do |redis|
redis.set APP_KEY, jwt
redis.expireat APP_KEY, payload[:exp]
end
end
end