Skip to content
Lucas Caton

How to test ElasticSearch in a Rails application

Lucas Caton

Lucas Caton

When I started using ElasticSearch in my Rails applications, I had a problem to create separate indexes for the automated tests.
The problem was: there is no way to create more than one database in ElasticSearch. You can create different indexes, but no different databases.
Even creating indexes with different names won't solve the problem: it's necessary to configure our Rails models in order to work with a different index name when the tests are running.
I'm using both tire and RSpec gems. In this post, I'll explain how to separate indexes for development and test environments.
First of all, I've included the code below in file config/initializers/tire.rb:
if Rails.env.test?
  prefix = "#{Rails.application.class.parent_name.downcase}_#{Rails.env.to_s.downcase}_"
And I've manually set the index name in the model (assuming there is a Movie model):
index_name "#{Tire::Model::Search.index_prefix}movies"
Done! With that, the index name will be movies in development environment and appname_test_movies in test environment.

Deleting test indexes

In order to delete the test indexes after the suite has finished running, just add the following code to file spec/integration_helper.rb (or similar):
RSpec.configure do |config|
  config.after(:all, type: :request) { delete_movie_index }
And create a custom macro, which will delete the indexes:
def delete_movie_index

Demo app

I created a small application to demonstrate the technique explained in this post:
I hope it helps!

Post updated at 02/10/2017, 10:00:00