Add the library to the test section in your application's Gemfile:
group :test do
gem 'testcontainers-redpanda'
endAnd then execute:
$ bundle installOr install it yourself as:
$ gem install testcontainers-redpandaCreate a new instance of the Testcontainers::RedpandaContainer class:
container = Testcontainers::RedpandaContainer.newThis creates a new container with the default MariaDB image. You can customize it by passing arguments to the constructor:
container = Testcontainers::MariadbContainer.new("vectorized/redpanda")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.mapped_port(9092)or
connection_url = container.connection_urlUse these connection details to connect to the Redpanda container using your preferred Kafka client library.
Here's a complete example of how to use testcontainers-redpanda to create a container, connect an consumer and a producer to it, and deliver one message:
require "testcontainers/redpada"
require "rdkafka"
container = Testcontainers::RedpandaContainer.new
container.start
config = {
"bootstrap.servers": container.connection_url,
"group.id": "ruby-test"
}
consumer = Rdkafka::Config.new(config).consumer
consumer.subscribe("ruby-test-topic")
producer = Rdkafka::Config.new(config).producer
producer.produce(payload: "Hello, Redpanda!", topic: "ruby-test-topic").wait
message = consumer.each do |msg|
break msg
end
puts msg.inspect
container.stopYou can manage the Redpanda container in the before(:suite) / after(:suite) blocks in your spec_helper.rb:
RSpec.configure do |config|
# This helps us to have access to the `RSpec.configuration.redpanda_container` without using global variables.
config.add_setting :redpanda_container, default: nil
config.before(:suite) do
config.redpanda_container = Testcontainers::RedpandaContainer.new.start
# Use the container connection details in your tests
end
config.after(:suite) do
config.redpanda_container&.stop
config.redpanda_container&.remove
end
endBug 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.