問題
redis-rb gemsを2.2から3.0.1にアップデートしたとき,sporktを使ってspecを走らせると以下のようなエラーが出た.
Tried to use a connection from a child process without reconnecting. You need to reconnect to Redis after forking.
原因
redis-rb 3以降では,forkしたときに親と子でredisのコネクションを共有していると例外を投げるようになったらしい.
ref: https://github.com/redis/redis-rb/blob/master/lib/redis/client.rb#L277
対処
sporkがforkしたときに再度コネクションを確立するようにSpork.each_run
内に以下のようなコードを書く.
spec_helper.rb
Spork.each_run do
# This code will be run each time you run your specs.
load Rails.root.join('config/initializers/redis.rb')
end
config/initializers/redis.rb
$redis = Redis.new(:host => 'localhost', :port => 6379)
$redis.ping
$redis.pingしてるのはRedis接続をチェックしてからRailsサーバー起動にあるハック
Unicornでも同じように,
- before_forkで
$redis.quit
- after_forkでRedisコネクションを作成
という処理が必要.