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
    hostname: localhost
    port: 8981
    log_level: WARNING

  <<: *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 =$original_sunspot_session)

Before("@search") do
  unless $sunspot
    $sunspot =
    pid = fork do
    # shut down the Solr server
    at_exit { Process.kill('TERM', pid) }
    # wait for solr to start
    sleep 5
  Sunspot.session = $original_sunspot_session


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.


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.