We recently started using Elasticsearch::Ruby
on our project and wanted to add some rspec integration tests. The documentation skips over rspec integration but by adapting their sample tests:
group :test do
# Add after other requires. Rake needs to be loaded.
RSpec.configure do |config|
# Snipped other config.
config.before :each, elasticsearch: true do
Elasticsearch::Extensions::Test::Cluster.start(port: 9200) unless Elasticsearch::Extensions::Test::Cluster.running?
config.after :suite do
Elasticsearch::Extensions::Test::Cluster.stop(port: 9200) if Elasticsearch::Extensions::Test::Cluster.running?
It’s important to namespace the index somehow so that your environments don’t clash. We used this.
class User < ActiveRecord::Base
index_name [Rails.env, model_name.collection.gsub(///, '-')].join('_')
Then you can add the elasticsearch tag to your rspec blocks:
describe 'Searching for a user', elasticsearch: true do
# Create and destroy Elasticsearch indexes
# between tests to eliminate test pollution
User.__elasticsearch__.create_index! index: User.index_name
# There are two options for how you create your objects
# 1. Create your objects here and they should be synchronised
# through the Elasticsearch::Model callbacks
# 2. Call import on the model which should reindex
# anything you've "let!"
# Sleeping here to allow Elasticsearch test cluster
# to index the objects we created
User.__elasticsearch__.client.indices.delete index: User.index_name
About the Author
More Content by James Robert Somers