简体   繁体   English

如何使用RSpec测试ThinkingSphinx

[英]How to test ThinkingSphinx using RSpec

I have a class method in a model that calls thinking_sphinx's search() method. 我在模型中有一个类方法,它调用thinking_sphinx的search()方法。 I need to check this class method. 我需要检查这个类方法。

I want to start, index or stop sphinx in my rspec test cases. 我想在我的rspec测试用例中启动,索引或停止sphinx。 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 如果您在think_sphinx中使用rspec,请引导我使用代码示例

Following David post, we end up with following solution: 在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

It switch specified tables to :truncation strategy, and after that switch them back to :trasaction strategy. 它将指定的表切换为:截断策略,然后将它们切换回:trasaction strategy。

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. 虽然ActiveRecord可以在单个事务中运行其所有操作,但Sphinx无法访问它,因此索引不包括您的事务的更改。

You have to disable your transactional fixtures. 你必须禁用你的交易固定装置。

In your rspec_helper.rb put 在你的rspec_helper.rb中

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

to disable globally. 全局禁用。

See Turn off transactional fixtures for one spec with RSpec 2 请参阅使用RSpec 2关闭一个规格的事务夹具

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM