使用RSpec测试searchkick

mfa*_*dor 6 rspec ruby-on-rails

我想在我的练习管理应用程序中创建用于搜索患者的功能规范.

到目前为止,我已经搜索了网络,并遵循以下建议的解决方案:

http://bitsandbit.es/post/11295134047/unit-testing-with-tire-and-elastic-search#disqus_thread

https://github.com/karmi/tire/wiki/Integration-Testing-Rails-Models-with-Tire

这两篇文章都建议为ElasticSearch和Tire配置spec_helper.rb.由于Searchkick基于Tire,我将解决方案应用于Patient类,这是我使用Searchkick的唯一模型.

但是,我得到每个配置的'NoMEthodError'.例如,使用以下代码:

spec_helper.rb

RSpec.configure do |config| do
  .
  .
  .

  config.before :each do
    Patient.index.delete
    Patient.create_elasticsearch_index
  end

  config.before :all do
   Patient.index_name('test' + Patient.model_name.plural)
  end
end
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

Failure/Error: Unable to find matching line from backtrace
 NoMethodError:
   undefined method `index_name' 
Run Code Online (Sandbox Code Playgroud)

方法'index'和'create_elasticsearch_index'也是如此

我对RoR很新,老实说我不确定我在这里做错了什么,除了假设我可以在Searchkick上使用Tire解决方案.所以任何帮助都非常感谢!

And*_*ane 30

Searchkick需要更好的测试文档,但这里有它的要点:

Searchkick会在每个环境中自动使用不同的索引名称,因此无需进行任何设置.Patient.searchkick_index.name在控制台中运行以确认这一点.

您可以直接调用,而不是删除和重新创建索引reindex.

RSpec.configure do |config| do
  config.before :each do
    Patient.reindex
  end
end
Run Code Online (Sandbox Code Playgroud)

最后,插入数据后,在调用Patient.searchkick_index.refresh之前调用Patient.search.这告诉Elasticsearch立即更新索引(而不是刷新间隔后,默认为1秒).

  • 真棒!你是一个绝对的救生员:D并且非常感谢宝石,因为它为我设置ElasticSearch节省了大量时间. (3认同)
  • @ andrew-kane,如果使用let!在我的规范中插入数据之后,我似乎只能使rspec正常工作,我只是在before块中调用Model.reindex。如果我调用Model.searchkick_index.refresh,则不会插入数据。我可以在应用程序中验证插入数据后可以轻松搜索索引。我没有做任何特别的事情(即没有异步或批量)。 (2认同)

Pet*_*vin -3

即使 Searchkick 基于 Tire,也不意味着 Tire 方法可在您的模型上使用。有关可用方法的文档,参阅https://github.com/ankane/searchkick请参阅https://github.com/ankane/searchkick#migration-from-tire小节,特别了解使用 Searchkick 和使用 Tire 之间的对比。