Ir para conteúdo principal
Lucas Caton

How to test ElasticSearch in a Rails application

Lucas Caton

Lucas Caton

@lucascaton
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:
ruby
if Rails.env.test?
  prefix = "#{Rails.application.class.parent_name.downcase}_#{Rails.env.to_s.downcase}_"
  Tire::Model::Search.index_prefix(prefix)
end
And I've manually set the index name in the model (assuming there is a Movie model):
ruby
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):
ruby
RSpec.configure do |config|
  config.after(:all, type: :request) { delete_movie_index }
end
And create a custom macro, which will delete the indexes:
ruby
def delete_movie_index
  Movie.index.delete
end

Demo app

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

Post atualizado em 02/10/2017, 10:00:00