Rspec with Elasticsearch::Ruby and Elasticsearch::Model

May 26, 2014 James Robert Somers

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'
# 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?

  config.after :suite do
    Elasticsearch::Extensions::Test::Cluster.stop(port: 9200) if Elasticsearch::Extensions::Test::Cluster.running?
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('_')
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
    # 2. Call import on the model which should reindex
    # anything you've "let!"

    # Sleeping here to allow Elasticsearch test cluster
    # to index the objects we created
    sleep 1

  after do
    User.__elasticsearch__.client.indices.delete index: User.index_name

About the Author


World's Smallest IaaS, Part 3: the PaaS
World's Smallest IaaS, Part 3: the PaaS

a.k.a. The World’s Smallest PaaS In this blog post, we describe deploying Cloud Foundry/Elastic Runtime to ...

Pivot with PaaS: How PaaS Will Help Your Business Survive and Thrive
Pivot with PaaS: How PaaS Will Help Your Business Survive and Thrive

For many businesses, the digital age has been disruptive. Many companies that were household names in 2000,...