Both the answers are outdated in May 2022. Following is the updated version with a sample test.
add this to Gemfile
gem 'mock_redis'
Install the mock_redis
gem using
bundle install
In your spec_helper.rb
or rails_helper.rb
add this
require 'mock_redis'
RSpec.configure do |config|
'''
Creating a stub/mock Redis for running the tests without requiring an actual Redis server. This will store the Redis data in memory instead of the Redis server.
'''
config.before(:each) do
mock_redis = MockRedis.new
allow(Redis).to receive(:new).and_return(mock_redis)
end
end
This would make sure to mock Redis for all your test.
Let's say you have a module (module_in_my_app.rb
) that uses Redis like so
module ModuleInMyApp
extend self
@@redis = Redis.new(url: "redis://#{ENV["REDIS_URL"]}")
def get_or_create_my_key(keys, default_value)
return @@redis.set(key, value)
end
def get_my_key(key)
return @@redis.get(key)
end
end
You can use it like so in your spec (module_in_my_app_spec.rb
)
describe "test my redis module" do
it "should set the key" do
ModuleInMyApp.set_my_key("US", "United States of America")
redis_var = class_variable_get(:@@redis)
expect(redis_var.get("US")).to eq("United States of America")
end
it "should get the key" do
mock_redis = Redis.new
mock_redis.set("CA", "Canada")
ModuleInMyApp.class_variable_set(:@@redis, mock_redis)
actual_result = ModuleInMyApp.get_my_key("CA")
expect(actual_result).to eq("Canada")
end
end
REDIS.flushdb
– Trephine