如何使用RSpec测试ThinkingSphinx

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

我想在我的rspec测试用例中启动,索引或停止sphinx。 我正在尝试这段代码。

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

在我触发搜索查询之前,在每个测试用例中使用此代码

 ThinkingSphinx::Test.index 

但是在我触发搜索查询后,它仍然给出了空结果,尽管测试数据库中存在完全匹配。

如果您在think_sphinx中使用rspec,请引导我使用代码示例

在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 

它将指定的表切换为:截断策略,然后将它们切换回:trasaction strategy。

这是由于交易固定装置

虽然ActiveRecord可以在单个事务中运行其所有操作,但Sphinx无权访问,因此索引不包括您的事务的更改。

你必须禁用你的交易固定装置。

在你的rspec_helper.rb中

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

全局禁用。

请参阅使用RSpec 2关闭一个规格的事务性灯具