testcontainers-redis simplifies the creation and management of Redis containers for testing purposes using the Testcontainers library.
Add the library to the test section in your application's Gemfile:
group :test do
gem 'testcontainers-redis'
endAnd then execute:
$ bundle installOr install it yourself as:
$ gem install testcontainers-redisTo use the library, you first need to require it:
require 'testcontainers/redis'Create a new instance of the Testcontainers::RedisContainer class:
container = Testcontainers::RedisContainer.newThis creates a new container with the default Redis image. You can customize these by passing arguments to the constructor:
container = Testcontainers::RedisContainer.new("redis:6.0-alpine", password: "custom_pass")Start the container:
container.startStop the container when you're done:
container.stopOnce the container is running, you can obtain the connection details using the following methods:
host = container.host
port = container.first_mapped_portOr, you can generate a full Redis URL:
redis_url = container.redis_urlUse this URL to connect to the Redis container using your preferred Redis client library.
You can also customize the container before of starting it, e.g setting a custom password for client's authentication:
container.with_password("custom_pass")or using a custom redis.conf (saved under $PWD/custom/conf in this
example):
container.with_filesystem_binds(["#{Dir.pwd}/custom/conf:/usr/local/etc/redis:rw"])
container.with_cmd("redis-server /usr/local/etc/redis/redis.conf")Here's a complete example of how to use testcontainers-redis to create a container, connect to it, and run a simple command:
require 'testcontainers/redis'
require 'redis'
container = Testcontainers::RedisContainer.new
container.start
client = Redis.new(url: container.redis_url)
client.set("mykey", "hello world")
value = client.get("mykey")
puts value
client.quit
container.stopThis example creates a Redis container, connects to it using the redis gem, sets and retrieves a key-value pair, and then stops the container.
Take a look to the files examples/redis_container_rspec.rb for a example using RSpec.
Bug reports and pull requests are welcome on GitHub at https://github.com/testcontainers/testcontainers-ruby. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the code of conduct.
The gem is available as open source under the terms of the MIT License.
Everyone interacting in the Testcontainers project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the code of conduct.