Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to stub redis in rspec tests

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.

like image 475
Matt Huggins Avatar asked Sep 07 '13 21:09

Matt Huggins


2 Answers

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 }
like image 80
Matt Huggins Avatar answered Nov 18 '22 00:11

Matt Huggins


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

like image 4
Tsvetelina Borisova Avatar answered Nov 18 '22 02:11

Tsvetelina Borisova