opensoul.org

Cucumber and Sunspot

April 7, 2010 code 2 min read

If you haven’t checked out Sunspot yet, you should. I have tried every solution for doing real full-text searching in a Rails app. Sunspot, backed by solr, is the only one that I haven’t had issues with in production. Hopefully I’ll get around to posting more about my experience with it.

But for today, here’s how I got Sunspot working with Cucumber.

First, add a configuration for the cucumber environment in config/sunspot.yml. I usually just use the same settings as test.

test: &TEST
  solr:
    hostname: localhost
    port: 8981
    log_level: WARNING

cucumber:
  <<: *TEST

Then, throw this bit of nastiness in the bottom of your env.rb file.

$original_sunspot_session = Sunspot.session

Before("~@search") do
  Sunspot.session = Sunspot::Rails::StubSessionProxy.new($original_sunspot_session)
end

Before("@search") do
  unless $sunspot
    $sunspot = Sunspot::Rails::Server.new
    pid = fork do
      STDERR.reopen('/dev/null')
      STDOUT.reopen('/dev/null')
      $sunspot.run
    end
    # shut down the Solr server
    at_exit { Process.kill('TERM', pid) }
    # wait for solr to start
    sleep 5
  end
  Sunspot.session = $original_sunspot_session

  MyModel.remove_all_from_index!
end

This will start up Sunspot for scenarios tagged with @search, and mock out the sunspot connection for ones that aren’t.

This content is open source. Suggest Improvements.

@bkeepers

avatar of Brandon Keepers I am Brandon Keepers, and I work at GitHub on making Open Source more approachable, effective, and ubiquitous. I tend to think like an engineer, work like an artist, dream like an astronaut, love like a human, and sleep like a baby.