Testing with Sunspot and Cucumber
This post is part of our Exploring Solr and Sunspot series.
Testing with sunspot with cucumber can be tricky since you need to manage the solr process separately. At Collective Idea, we have adopted a practice where we would tag our cucumber features and cucumber would automatically start/stop solr as needed, and its worked great. So great in fact that I decided to roll it into a gem so you can also enjoy it.
Today I released sunspot_test and an example codebase on how to use it.
It’s rather simple actually, if you have a cucumber scenario (or an entire feature) that needs to use solr for anything you just tag it with
@search. For example:
@search Feature: Books Scenario: Searching for a book Given a book exists with a title of "Of Mice and Men" And I am on the books page And I fill in "query" with "Mice" When I press "Search!" Then I should see "Of Mice and Men"
This feature will first start an instance of solr based on your configuration in
RAILS_ROOT/config/sunspot.yml, then let the codebase correctly update solr when the book is created, then let the codebase query the solr server for a book, and finally shut down the solr instance when cucumber is done. Its that easy!
If you start to run into odd issues, I’d recommend doing a search for existing java processes. Sometimes in an erroneous run, a solr process will be orphaned. You can search and kill the java processes with the following:
ps aux | grep solr # this will search existing processes for a solr process. kill # this will kill the process with the given PID.
After we integrated this gem with one of our projects, I realized I broke a couple things. The latest release on rubygems is updated.
First, to enable functionality you have to require the following in your cucumber
# in env.rb require 'sunspot_test/cucumber'
Secondly, if your test does not use the
search tag then the test will use a proxy object which silently swallows the solr requests/updates. So now you only have to use the
search tag for tests that actually query solr.
Finally, there is a new
SunspotTestHelper.startup_timeout that lets you configure the timeout where the codebase waits for the solr process to start.
Check out the README and if you have any issues feel free to email me or create an issue on the github respository.
Zach, I’ll take a look at your gem because we’ll likely end up using it. In our implementation we simply force an index of each model via a cucumber step . . . I know, I know, it’s inefficient.
Thanks for this.
@diebels727 Not a problem! Let me know via github if you run into any issues.
Handy! I’ve been wondering when someone would create a gem for this :)
Thanks for this gem. Definitely helps ensure solr tests are working properly.
Using it with rspec. Placed the require statement inside spork.prefork. Now can run most tests w/o sunspot/solr and when needed the :search => true gives it back. Surprised how fast it loads in the test environment. Well done.