Skip to content
Chris Hough edited this page Aug 28, 2016 · 7 revisions

If you need to create short-lived, standalone Redis processes for the purpose of running your specs, this works beautifully:

RSpec.configure do |config|
  REDIS_PID = "#{Rails.root}/tmp/pids/redis-test.pid".freeze
  REDIS_CACHE_PATH = "#{Rails.root}/tmp/cache/".freeze

  config.before(:suite) do
    redis_options = {
      'daemonize'     => 'yes',
      'pidfile'       => REDIS_PID,
      'port'          => 9_736,
      'timeout'       => 300,
      'save 900'      => 1,
      'save 300'      => 1,
      'save 60'       => 10_000,
      'dbfilename'    => 'dump.rdb',
      'dir'           => REDIS_CACHE_PATH,
      'loglevel'      => 'debug',
      'logfile'       => 'stdout',
      'databases'     => 16
    }.map { |k, v| "#{k} \"#{v}\"" }.join("\n")
    `echo '#{redis_options}' | redis-server -`
  end

  config.after(:suite) do
    `
      cat "#{REDIS_PID}" | xargs kill -QUIT
      rm -f "#{REDIS_CACHE_PATH}dump.rdb"
    `
  end
end

If you're not using Rails, you must set the redis server in Resque:

Resque.redis = Redis.new(:host => 'localhost', :port => 9736, :thread_safe => true)  

and change REDIS_PID and REDIS_CACHE_PATH paths to your own location.

You might also like mock_redis if you don't need full-on live integration tests all the time (but you might also just have Resque.inline set for most of your test suite).