Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a gem to test Redis logic in Rails?

Like Database cleaner, or the default clearing of the data store after a test run. I searched and couldn't find one. It could be either a separate test data store or just something simple that namespaces all Redis commands into a test namespace.

If anyone knows of any lemme know, otherwise I'll write one and OS it :)

like image 679
ambertch Avatar asked Nov 27 '11 06:11

ambertch


2 Answers

When working with rails and redis I use a different redis db or namespace for the different environments. The setup is very simple and similar to ActiveRecords database config.

First, create a config: (namespace version commented out)

#config/redis.yml
default:
  host: localhost
  port: 6379
development:
  db: 0
#  namespace: appname_dev
test:
  db: 1
#  namespace: appname_test
production:
  db: 2
  host: 192.168.1.100
#  namespace: appname_prod

Then load the config and connect to redis through an initializer:

#config/initializers/redis.rb
REDIS_CONFIG = YAML.load( File.open( Rails.root.join("config/redis.yml") ) ).symbolize_keys
dflt = REDIS_CONFIG[:default].symbolize_keys
cnfg = dflt.merge(REDIS_CONFIG[Rails.env.to_sym].symbolize_keys) if REDIS_CONFIG[Rails.env.to_sym]

$redis = Redis.new(cnfg)
#$redis_ns = Redis::Namespace.new(cnfg[:namespace], :redis => $redis) if cnfg[:namespace]

# To clear out the db before each test
$redis.flushdb if Rails.env == "test"

Remember to add 'redis-namespace' to your Gemfile if your using that version.

like image 123
jlundqvist Avatar answered Oct 14 '22 16:10

jlundqvist


You can try fakeredis. It is an fake redis implementation written in pure ruby.

like image 45
miaout17 Avatar answered Oct 14 '22 15:10

miaout17