Skip to content

Instantly share code, notes, and snippets.

@mreinsch
Last active October 8, 2015 04:32
Show Gist options
  • Save mreinsch/094dc9cf63362314cef4 to your computer and use it in GitHub Desktop.
Save mreinsch/094dc9cf63362314cef4 to your computer and use it in GitHub Desktop.
elasticsearch rspec helpers, add to spec/support
# some helpers to make integration testing with elasticsearch easier
# expects Capybara
# modify this!
MODELS_WITH_ELASICSEARCH_MODEL = [Group, Event]
begin
MODELS_WITH_ELASICSEARCH_MODEL.each do |c|
c.__elasticsearch__.create_index! force: true
c.__elasticsearch__.refresh_index!
end
rescue => err
if ENV['CONTINUOUS_INTEGRATION']
raise "elasticsearch not running: #{err}"
else
puts "elasticsearch not running => disabled specs which require elasticsearch"
RSpec.configure do |c|
c.filter_run_excluding require_elasticsearch: true
end
end
end
module ElasticsearchHelperMethods
def wait_for_elasticsearch(object, accessor_or_keyword)
keyword = accessor_or_keyword.is_a?(Symbol) ? object.send(accessor_or_keyword) : accessor_or_keyword
expected_object_id = object.id.to_s
query = {
query: {
bool: {
must: [
{ ids: { type: object.class.model_name.singular, values: [expected_object_id] } },
{ query_string: { query: keyword } }
]
}
}
}
wait_for_elasticsearch_query(object.class, query)
end
def wait_for_elasticsearch_query(object_class, query, opts={})
counter = 0
exists_query = opts.merge(index: object_class.index_name, body: query)
begin
Elasticsearch::Model.client.search_exists(exists_query)
rescue Elasticsearch::Transport::Transport::Errors::NotFound
counter += 1
sleep 0.3
if counter >= Capybara.default_wait_time * 3
raise "expected to find '#{query}' in search index, but no result"
else
retry
end
end
end
def wait_for_elasticsearch_removal(object)
counter = 0
exists_query = {index: object.class.index_name, type: object.class.model_name.singular, id: object.id}
while Elasticsearch::Model.client.exists?(exists_query)
counter += 1
sleep 0.3
if counter >= Capybara.default_wait_time * 3
raise "expected exists for '#{exists_query}' to return false"
end
end
end
def clear_elasticsearch!
indexes = MODELS_WITH_ELASICSEARCH_MODEL.map {|c| c.index_name }
Elasticsearch::Model.client.delete_by_query(index: indexes, body: {query: { match_all: {} } })
end
end
RSpec.configuration.include ElasticsearchHelperMethods
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment