Writing tests with RSpec for Redis with Rails

I like to have redis running while the tests are running. Redis, unlike e.g. postgres, is extremely fast and doesn't slow down test run time noticeably.

Just make sure you call REDIS.flush in a before(:each) block, or the corresponding cucumber hook.

You can test data_to_cache independently of redis, but unless you can fully trust the redis driver you're using and the contract it provides, it's safer to actually test cache_data (and the corresponding cache fetch method) live. That also allows you to switch to a different redis driver (or to a different fast KV store) without a wholesale rewrite of your tests.


First of all add the below code in the spec_helper.rb so you'll be sure that the tests will run on any machine even if the redis server is not installed (make sure to add to your gemfile mock_redis under test scopes:

redis_instance = MockRedis.new
Redis.stub(:new).returns(redis_instance)
Redis::Store.stub(:new).returns(redis_instance)

After that I would test:

  1. The data written to REDIS is the expected data
  2. A sequence of cache_data, flush_data, cache_data calls the data_to_cache twice