I was wondering if anyone has a clever way of testing behavior after a redis key expires. I am essentially building a small redis backed cache for my application and would like to test what happens after a redis key is set to expire.
I am using rspec as my testing framework. I tried to use Timecop to change the time during testing but realized that it would only effect the testing frame work and not the external redis server.
I can set the TTL to 1 and then use a sleep(1) but I would rather not introduce sleeps into my tests.
Does anyone have a good way of testing this?
Normally Redis keys are created without an associated time to live. The key will simply live forever, unless it is removed by the user in an explicit way, for instance using the DEL command.
All the Redis objects have an expiration time. By default, the value is set to never. However, by changing this value, we can set Redis keys that will expire automatically after a fixed amount of time. Once the expiration time is passed, the key is deleted from the database.
Redis is an in-memory data structure store, used as a distributed, in-memory key–value database. And TTL stands for Time-to-Live. While setting a key in Redis, you can specify the time to live for key when the TTL elapses, the key is automatically destroyed.
Why not use http://redis.io/commands/expire to expire the key right away?
The proper way to fix this for the testing environment is to mock out the redis client and have it return the expected value. I have confidence redis will do the right thing and is implemented correctly so mocking this interaction out is probably better than letting the test actually hit redis.
redis_client.should_receive(:ttl).with(key).then_return(-1)
or just mock out the request for the key
redis_client.should_receive(:get).with(key).then_return(nil)
With the newer RSpecs version,
expect(redis_client).to receive(:get).with(key).and_return(value)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With