Question

I'm trying to stub redis using the mock_redis gem for my rspec tests. My rspec config looks like this:

RSpec.configure do |config|
  # ... various rspec config options ...

  config.before(:each) do
    redis_instance = MockRedis.new
    Redis.stub(:new).and_return(redis_instance)
    Redis::Store.stub(:new).and_return(redis_instance)
  end
end

Unfortunately, I'm still seeing gets and sets being sent to my actual redis instance, and if I kill redis, then my tests all fail. I tried adding a breakpoint, and I do see that this block of code is properly being executed. I also confirmed that from within the scope of this before block, both Redis.new == redis_instance and Redis::Store.new == redis_instance are true.

Does anyone have any insight as to why this isn't working for me? I'm open to alternate approaches for stubbing/mocking redis as well.

Was it helpful?

Solution

It looks like passing a block instead of a value to and_return makes it work, though I'm not sure why. e.g.:

Redis.stub(:new).and_return { redis_instance }
Redis::Store.stub(:new).and_return { redis_instance }

OTHER TIPS

I am also having a problem with mock_redis. I found fakeredis https://github.com/guilleiguaran/fakeredis which decided my problems.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top