Kevin Bedell Kevin Bedell - 1 year ago 135
Ruby Question

Writing tests with RSpec for Redis with Rails

I have a model class that caches data in redis. The first time I call a method on the model, it computes a JSON/Hash value and stores it in Redis. Under certain circumstances I 'flush' that data and it gets recomputed on the next call.

Here's the code snippet similar to the one I use to store the data in Redis:

def cache_data
self.data_values = data_to_cache

def data_to_cache
// generate a hash of values to return

How should I unit test this code? I use RSpec and Capybara. I also use Cucumber and Capabara for integration testing if that helps.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download