How to test ThinkingSphinx using RSpec
Asked Answered
L

2

9

I have a class method in a model that calls thinking_sphinx's search() method. I need to check this class method.

I want to start, index or stop sphinx in my rspec test cases. I am trying with this piece of code.

before(:all) do
  ThinkingSphinx::Test.start
end

after(:all) do
  ThinkingSphinx::Test.stop
end

and with this code in each test case before I fire the search query

ThinkingSphinx::Test.index

but still after I fire the search query, it gives me empty results though exact matches are there in the test db.

Please guide me with code examples if you are using rspec with thinking_sphinx

Lapoint answered 11/11, 2010 at 10:59 Comment(1)
We have TS in a project that needs to index 600k articles. It's a big bucket of FAIL. Testing (as you found out) is a real pain in the *ss. We're moving to SunSpot, which utilises Solr.Homeomorphism
B
13

Following David post, we end up with following solution:

#spec/support/sphinx_environment.rb
require 'thinking_sphinx/test'

def sphinx_environment(*tables, &block)
  obj = self
  begin
    before(:all) do
      obj.use_transactional_fixtures = false
      DatabaseCleaner.strategy = :truncation, {:only => tables}
      ThinkingSphinx::Test.create_indexes_folder
      ThinkingSphinx::Test.start
    end

    before(:each) do
      DatabaseCleaner.start
    end

    after(:each) do
      DatabaseCleaner.clean
    end

    yield
  ensure
    after(:all) do
      ThinkingSphinx::Test.stop
      DatabaseCleaner.strategy = :transaction
      obj.use_transactional_fixtures = true
    end
  end
end

#Test
require 'spec_helper'
require 'support/sphinx_environment'

describe "Super Mega Test" do
  sphinx_environment :users do
    it "Should dance" do
      ThinkingSphinx::Test.index
      User.last.should be_happy
    end
  end
end

It switch specified tables to :truncation strategy, and after that switch them back to :trasaction strategy.

Bronze answered 14/2, 2012 at 13:1 Comment(2)
If you have any comment feel free to post them.Bronze
@Bronze Your code looks promising. Where should the code "ThinkingSphinx::Test.init" be placed? Also where should Factory_Girl's data creation code be placed? I had trouble getting them to work. The resulted empty web page generated. I suspected that either TS not seeing the data or TS not started/indexed right.Zamudio
H
4

This is due to transactional fixtures.

While ActiveRecord can run all its operations within a single transaction, Sphinx doesn’t have access to that, and so indexing will not include your transaction’s changes.

You have to disable your transactional fixtures.

In your rspec_helper.rb put

RSpec.configure do |config|
  config.use_transactional_fixtures = false
end

to disable globally.

See Turn off transactional fixtures for one spec with RSpec 2

Haeckel answered 9/2, 2011 at 10:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.