In previous posts I blogged about using Redis to store data. The question is how to test the code that leverages this data?
When your Rails tests use records from the main DB (MySQL, PG, Mongo) you can use gems like FactoryGirl and DatabaseCleaner to get data into the right state for your tests. How do you do the same with Redis?
Configure Redis connection in config/initializers/redis.rb
Here we have app/services/redis_service_object.rb that returns values of all keys in Redis.
This solution works well when you have a few objects accessing data in Redis and you can just create the data in your tests. This approach is not very DRY if you have lots of code that needs to be tested. In that case you could create separate class(es) somewhere in spec/factories and call them from your test like any other Ruby class.
With mock_redis test data is never actually persisted into Redis. If that is not sufficient then instead of configuring MockReids in initializer you can use the real Redis connection (and have Redis server running). You could separate environment specific data by using different Redis DBs and/or namespaces.
There is also fakeredis gem but I could not make it work with latest Rspec, Rails and Redis. If someone knows how to use it, please leave a comment.