-
Notifications
You must be signed in to change notification settings - Fork 36
RSpec and Sunspot
If you want to prevent any test from running a Solr search, which you probably do, you can do so within your spec_helper.rb
as opposed to having to do it in lots of describe
blocks. The code below has been tested and works with sunspot
/sunspot-rails
v1.0.3
.
require 'sunspot/rails/spec_helper' Spec::Runner.configure do |config| config.before(:each) do ::Sunspot.session = ::Sunspot::Rails::StubSessionProxy.new(::Sunspot.session) end config.after(:each) do ::Sunspot.session = ::Sunspot.session.original_session end end
Note: This did not work as expected with Sunspot v 1.1.0. Instead, create a file called sunspot.rb
in the spec/support
folder, with the following line:
Sunspot.session = Sunspot::Rails::StubSessionProxy.new(Sunspot.session)
It’s also possible to start up a Solr instance for tests. This is what I came up with for v1.1.0 and Rails v2.3.8 (adapted from this blog post):
pid = fork { Sunspot::Rails::Server.new.run } sleep 5 # allow some time for the instance to spin up at_exit do `ps ax|egrep "solr.*test"|grep -v grep|awk '{print $1}'|xargs kill` end
Note that this works even if you have a Solr instance running for development, because Sunspot::Rails::Server is smart enough to create a different instance based on RAILS_ENV.
“Why not use Sunspot::Rails::Server.new.start, which spins off its own process and manages a pid file?” you might ask. Well, because something about the way it forks screws up Rails. Somehow it ends up running all the tests twice, with ActiveRecord’s database connection broken for half of them.