Rails:使用黄瓜和webrat集成测试thinking_sphinx - 如何索引事务夹具?

时间:2009-05-20 15:46:58

标签: ruby-on-rails cucumber thinking-sphinx webrat

我想对我的搜索功能使用thinking_sphinx & sphinx进行一些Cucumber / webrat集成测试,但问题是数据已加载,然后在典型的黄瓜测试期间在事务中回滚,因此存在think_sphinx无法为其编制索引。或者,有没有办法只针对一部分测试关闭交易?

你解决了这个问题吗?

[编辑 - 请不要建议嘲笑搜索结果。我希望集成测试能够测试所有功能的集成,包括thinking_sphinx]。

7 个答案:

答案 0 :(得分:2)

我在这个陈述中看到了问题:

  

在典型的黄瓜测试期间,数据被加载然后在事务中回滚,因此think_sphinx无法将其编入索引

将think_sphinx索引结果可能不是 fast ,但它在事务中肯定是可能的。由于它是单个集成测试,而不是针对您的(多个)单元测试中的每一个,我都会受到速度的影响。

所以现在你需要弄清楚如何在交易过程中触发重新索引。

# somewhere in /features/support:
before('@reindexing') do
  require 'Rake'

  class MyModel
    after_save :force_reindex!

    def force_reindex!
      # in case multiple runs of this block cause the hook
      # to get added multiple times, let's check to make sure
      # we haven't already reindexed for this save
      return if @__reindexed
      Rake["thinking_sphinx:rebuild"].execute
      @__reindexed = true
    end
  end
end

after('@reindexing') do
  class MyModel
    def force_reindex!
      # do nothing; the hook still gets called, but that's ok
    end
  end
end

/features/integration.feature(或其他),你有

@reindexing
Feature: The whole shebang, altogether

  Scenario: ...

答案 1 :(得分:2)

通过使用数据库清理器插件并修改我们的功能/ support / env.rb,我们能够通过思考sphinx成功地运行我们的黄瓜测试:

# Sets up the Rails environment for Cucumber
ENV["RAILS_ENV"] ||= "cucumber"

...

# http://github.com/bmabey/database_cleaner
require 'database_cleaner'
DatabaseCleaner.strategy = :truncation
Before do
  DatabaseCleaner.clean
end

ThinkingSphinx::Configuration.instance.build
ThinkingSphinx::Configuration.instance.controller.start
at_exit do
  ThinkingSphinx::Configuration.instance.controller.stop
end
ThinkingSphinx.deltas_enabled = true
ThinkingSphinx.updates_enabled = true
ThinkingSphinx.suppress_delta_output = true

# Re-generate the index before each Scenario
Before do
  ThinkingSphinx::Configuration.instance.controller.index
end

正如您所看到的,我们还创建了一个'黄瓜'环境和一个单独的数据库(为了同时运行黄瓜和规格而不会发生冲突) - 所以你需要在database.yml中添加一个'cucumber:'条目和sphinx.yml如果你也愿意这样做。

答案 2 :(得分:1)

链接的建议不起作用,因为Rake任务在单独的进程中调用索引器,因此在测试事务之外。

除了关闭测试事务以外,我不知道除此之外还有什么方法可以让sphinx索引进程看到新的和更新的记录。为此,请在TestCase中添加

self.use_transactional_fixtures = false

请记住,您需要在测试结束时管理清理任何数据。

答案 3 :(得分:0)

我不建议你测试一个你不拥有的组件。这将是一个非常脆弱的测试,因为它将依赖于特定版本的sphinx中的特定排名算法,该算法可能会在以后发生变化,从而在将来返回不可预测的结果。

如果你想这样做我会建议运行一个单独的索引来测试使用测试数据库通过mysql适配器或xmlpipe2选项(xml2pipe显然可以让你更改你的数据集,而无需更改你的索引选项sphinx文件)。这可能需要您一次单独设置测试数据,删除索引(使用ruby shell命令),然后强制重建索引(等待索引文档的总数与已知的数据库记录数相同)并根据数据运行测试。

我真的要小心不要测试索引,就像我说你可能只是发现自己不得不处理不断破坏的测试或慢速测试运行时(取决于你索引的数据量)

答案 4 :(得分:0)

这可能比它的价值更麻烦,但你试过开启delta指数吗?

答案 5 :(得分:0)

我尝试了建议的解决方案,但是sphinx超时,出现以下错误。在启用事务性灯具时,我认为不可能重新索引sphinx。

错误:index'socument_core':sql_query_pre [0]:超出锁定等待超时;尝试重新启动交易

答案 6 :(得分:0)

使用标签分隔黄瓜思维狮身人面像测试的另一个例子,使用黄瓜标签here