Unit Testing Sphinx

Sphinx (and its rails plugin thinking-sphinx) is my choice of search engine on ruby/rails project. It is powerful yet super easy to setup.

However, testing Sphinx code is not easy at first. Since Sphinx works by leverging database commit hooks, it cannot be tested within the bounds of unit testing framework that rails provides. This is understandable because, in rails testing, a transaction is started before each test that is bound to rollback after the test is finished. Since the test data is never committed, sphinx doesn't get a chance to index anything and cannot be tested.

The documentation for sphinx testing suggests using cucumber for integration testing. To me, cucumber test are still miles away from the smallest piece of sphinx code (inside Model) to be tested. So, I turned to how transactional code is tested in rails framework for some cue.

Here is what I ended up with:

 
class TransactionalUserTest < ActiveSupport::TestCase
  // any transactional test needs to have this
  self.use_transactional_fixtures = false
 
  context "with no users in database" do
    setup do
      // clear the existing data for our test - not sure if this affects other test but we use machinist instead of fixture files, so we should be good here.
      User.destroy_all
      UserProfile.destroy_all
    end
 
    context "with a few users created" do
      setup do
        @john = @david = nil
        // any data for sphinx test should be wrapped in transaction so sphinx can see these changes
        User.transaction do
          @john = User.make(:first_name => "John")
          @david = User.make(:first_name => "David")
        end
      end
      should "find user with first name john" do
        // start sphinx server
        ThinkingSphinx::Test.run do
          // give sphinx an opportunity to index newly added data (required before calling search)
          ThinkingSphinx::Test.index
          assert_equal([@john], User.search("john").collect)
          assert_equal([@david], User.search("david").collect)
          assert_equal([],User.search("cheese").collect)
        end
      end
    end
  end
end
 

Isn't it nicer to be able to test sphinx code in isolation :-)

Related posts:

  1. Testing various roles in ruby on rails
  2. Agile Development and Testing: Unit or Montecarlo?
  3. Unit Testing: Can You Afford Not To?
  4. Nested Contexts and Test Structure
  5. Elements of Testing Style

Comments: 1 so far

  1. [...] Unit Testing Sphinx | Pathfinder Development | Software Developers | Blogs [...]

    Pingback by Ennuyer.net » Blog Archive » Rails Reading February 14 2010, Sunday, February 14, 2010 @ 12:36 pm

Leave a comment

Powered by WP Hashcash

Launch: Pathfinder Newsletter

    Get a monthly update on best practices for delivering successful software.

    Subscribe via email


    Subscribe via RSS      RSS icon

Topics

Search

WordPress

Comments about this site: info@pathf.com