DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Alexey has posted 28 posts at DZone. View Full User Profile

Install And Test SOLR+Sunspot In Your Rails+RSpec Project

06.22.2011
| 11192 views |
  • submit to reddit
        SOLR is Lucene-based full text search server.
Sunspot is a Ruby gem that serves as adapter for SOLR.

IMHO this combination creates much better developer experience comparing to the alternatives that I've considered before.
Ferret just does not install on Windows. Its official site did not work yesterday. And I've seen that people report that it's instable.
Sphinx+Thinking Sphinx is quite robust alternative. Though it requires regular reindexing. It works only with MySQL & PostgreSQL databases. It installation process requires some manual steps.
ActAsSolrReloaded is not that actively maintained as Sunspot. It lacks documentation, tutorials etc.

Sunspot does not suffer from all those disadvantages. The only problem is configuring automated testing. We'll fix this problem below.
So let's start.

Adding SOLR+Sunspot to Rails project is trivial:

Add to Gemfile:
gem 'sunspot_rails', '~> 1.2.1' 

Add to .gitignore:
solr/data

Run:
bundle install
rails generate sunspot_rails:install
You might review config/sunspot.yml file.

Add to your model class (e.g. Post title:text user:references):
  searchable do
    text :title

    integer :user_id, :references => User
  end
 

Now you ready to test it:
$ rake sunspot:reindex
$ rake sunspot:solr:start
$ rails c

> Post.solr_search { keywords "something" }.results
> Post.solr_search { keywords "some title" ; with :user_id, 1 }.results

Most problematic part here is to create automated tests. 
See also http://blog.kabisa.nl/2010/02/03/running-cucumber-features-with-sunspot_rails/.

Create file spec/support/sunspot.rb:
require 'sunspot/rails/spec_helper'
require 'net/http'

try_server = proc do |uri|
  begin
    Net::HTTP.get_response uri
  rescue Errno::ECONNREFUSED
  end
end

start_server = proc do |timeout|

  server = Sunspot::Rails::Server.new
  uri = URI.parse("http://0.0.0.0:#{server.port}/solr/")

  try_server[uri] or begin

    server.start
    at_exit { server.stop }

    timeout.times.any? do
      sleep 1
      try_server[uri]
    end
  end
end

original_session = nil            # always nil between specs
sunspot_server = nil              # one server shared by all specs

if defined? Spork
  Spork.prefork do
    sunspot_server = start_server[60] if Spork.using_spork?
  end
end

RSpec.configure do |config|

  config.before(:each) do
    if example.metadata[:solr]    # it "...", solr: true do ... to have real SOLR
      sunspot_server ||= start_server[60] || raise("SOLR connection timeout")

    else
      original_session = Sunspot.session
      Sunspot.session = Sunspot::Rails::StubSessionProxy.new(original_session)
    end
  end

  config.after(:each) do
    if example.metadata[:solr]
      Sunspot.remove_all!

    else
      Sunspot.session = original_session
    end
    original_session = nil
  end
end

Now you can add to your specs:
    it "Sunspot works", :solr => true do
      e = Post.create!(:text => "xxx")
      Sunspot.commit
      results = Entry.solr_search { keywords "xxx" }.results
      results.size.should == 1
    end 

Pay attension to :solr => true. We've used it in support/sunspot.rb, to distinguish the test cases with real SOLR Server from those with a stubbed one.

Also pay attention to Sunspot.commit. It's required for your changes to SOLR index to be applied immediately. But default SOLR applies changes quite quickly, but with some delay. What is unacceptable for an automated test.

Also it works well with Spork.