LoginSignup
29
18

More than 5 years have passed since last update.

mock_redisを利用してテスト環境のRedisをmockする

Last updated at Posted at 2013-11-22

Redisのテスト

環境の切り替えはnamespaceとか使うべきなのかな…と思っていたらcauses/mock_redisを見つけました。

>> require 'mock_redis'
>> mr = MockRedis.new
>> mr.set('some key', 'some value')
=> "OK"
>> mr.get('some key')
=> "some value"

と言った形でredisの操作をmock出来るgemです。

RSpecへの適応

テスト実行時にlocalのredis等を使わないようにします。

spec_helper.rb
require 'mock_redis'

RSpec.configure do |config|
  config.before(:all) do
    # for Spring
    $redis.client.reconnect
  end
  config.before(:each) do
    redis_instance = MockRedis.new
    Redis.stub(:new).and_return{ redis_instance }
    # for redis cache.
    #Redis::Store.stub(:new).and_return{ redis_instance }
    # 追記
    $redis = Redis.new
  end

追記

initializerのタイミングがMockよりも先なのでspec_helper内で$redisを生成し直す形に変更しました。
と言うか今までMock出来てなかったのか…。

Redis.newした時にMockRedis.newを返します。
Springを利用している場合は

     Redis::InheritedError:
       Tried to use a connection from a child process without reconnecting. You need to reconnect to Redis after forking.

が出てしまうので、before(:all)内で再接続させています。
$redisはinitializers内で

config/initializers/redis.rb
redis_config = YAML.load_file(Rails.root.join('config', 'redis.yml'))[Rails.env]
$redis = Redis.new(:host => redis_config['host'], :port => redis_config['port'])

と言った感じで設定しています。

29
18
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
29
18