如何使用Rspec测试ThinkingSphinx

9

我在一个模型中有一个类方法,调用了thinking_sphinx的search()方法。我需要检查这个类方法。

我想在我的rspec测试用例中启动、索引或停止sphinx。我正在尝试使用以下代码:

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

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

在每个测试用例中,在执行搜索查询之前使用此代码。
ThinkingSphinx::Test.index

但是,即使在测试数据库中存在精确匹配项,当我执行搜索查询时,它仍然给出空结果。请使用代码示例指导我,如果您正在使用rspec和thinking_sphinx。


我们的项目中有一个需要索引60万篇文章的TS。这是一个巨大的失败。测试(正如你所发现的)真的很痛苦。我们正在转向SunSpot,它利用Solr。 - Ariejan
2个回答

13

按照 David 的帖子,我们得到以下解决方案:

#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

将指定的表切换到: 截断策略(truncation strategy),然后再切换回: 事务策略(transaction strategy)。


如果您有任何评论,请随意发表。 - Max
@Max,你的代码看起来很有前途。"ThinkingSphinx::Test.init" 代码应该放在哪里?同时,Factory_Girl的数据创建代码应该放在哪里?我在使用时遇到了一些问题,结果生成了空白的网页。我怀疑是TS没有看到数据或者TS没有正确启动或索引。 - GeorgeW

4
这是由于事务性固定装置引起的。
虽然ActiveRecord可以在单个事务中运行其所有操作,但Sphinx无法访问该事务,因此索引不会包括您事务的更改。
您必须禁用事务性固定装置。
在rspec_helper.rb中加入:
RSpec.configure do |config|
  config.use_transactional_fixtures = false
end

全局禁用。

请参见使用RSpec 2关闭一个测试的事务固定装置


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接