Skip to content

Instantly share code, notes, and snippets.

@rowanoulton
Last active January 12, 2019 16:12
Show Gist options
  • Save rowanoulton/1594ccbb70fa929dca63 to your computer and use it in GitHub Desktop.
Save rowanoulton/1594ccbb70fa929dca63 to your computer and use it in GitHub Desktop.
# spec/spec_helper.rb
RSpec.configure do |config|
# Create indexes for all elastic searchable models
config.before :each, elasticsearch: true do
ActiveRecord::Base.descendants.each do |model|
if model.respond_to?(:__elasticsearch__)
begin
model.__elasticsearch__.create_index!
model.__elasticsearch__.refresh_index!
rescue Elasticsearch::Transport::Transport::Errors::NotFound => e
# This kills "Index does not exist" errors being written to console
# by this: https://github.com/elastic/elasticsearch-rails/blob/738c63efacc167b6e8faae3b01a1a0135cfc8bbb/elasticsearch-model/lib/elasticsearch/model/indexing.rb#L268
rescue => e
STDERR.puts "There was an error creating the elasticsearch index for #{model.name}: #{e.inspect}"
end
end
end
end
# Delete indexes for all elastic searchable models to ensure clean state between tests
config.after :each, elasticsearch: true do
ActiveRecord::Base.descendants.each do |model|
if model.respond_to?(:__elasticsearch__)
begin
model.__elasticsearch__.delete_index!
rescue Elasticsearch::Transport::Transport::Errors::NotFound => e
# This kills "Index does not exist" errors being written to console
# by this: https://github.com/elastic/elasticsearch-rails/blob/738c63efacc167b6e8faae3b01a1a0135cfc8bbb/elasticsearch-model/lib/elasticsearch/model/indexing.rb#L268
rescue => e
STDERR.puts "There was an error removing the elasticsearch index for #{model.name}: #{e.inspect}"
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment