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:
# Gemfile group :test do gem 'elasticsearch-extensions' end
# spec_helper.rb # Add after other requires. Rake needs to be loaded. require 'rake' require 'elasticsearch/extensions/test/cluster/tasks' 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? end config.after :suite do Elasticsearch::Extensions::Test::Cluster.stop(port: 9200) if Elasticsearch::Extensions::Test::Cluster.running? end end
It’s important to namespace the index somehow so that your environments don’t clash. We used this.
class User < ActiveRecord::Base include Elasticsearch::Model include Elasticsearch::Model::Callbacks index_name [Rails.env, model_name.collection.gsub(///, '-')].join('_') end
Then you can add the elasticsearch tag to your rspec blocks:
describe 'Searching for a user', elasticsearch: true do before 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 User.create! # 2. Call import on the model which should reindex # anything you've "let!" User.import # Sleeping here to allow Elasticsearch test cluster # to index the objects we created sleep 1 end after do User.__elasticsearch__.client.indices.delete index: User.index_name end end
About the AuthorMore Content by James Robert Somers