我想知道在使用ElasticSearch和Tire时,您是如何在应用程序中测试搜索的.

  • 如何设置新的ElasticSearch测试实例?有办法嘲笑它吗?

  • 你知道有什么Ruby 能帮上忙吗?


我发现一些有用的东西:

我发现一篇很好的文章几乎回答了我所有的问题:)

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

我不敢相信我在问之前没有找到这些...

推荐答案

为当前环境添加索引名前缀

您可以 for each 环境设置不同的索引名(在您的示例中为测试环境).

例如,您可以在中创建初始值设定项

config/initializers/tire.rb

使用以下行:

Tire::Model::Search.index_prefix "#{Rails.application.class.parent_name.downcase}_#{Rails.env.to_s.downcase}"

一种删除索引的可行方法

假设您有名为Customer、Order和Product的模型,将以下代码放在测试启动/before block/each run block的某个地方.

# iterate over the model types
# there are also ways to fetch all model classes of the rails app automaticly, e.g.:
#   http://stackoverflow.com/questions/516579/is-there-a-way-to-get-a-collection-of-all-the-models-in-your-rails-app
[Customer, Order, Product].each do |klass|

  # make sure that the current model is using tire
  if klass.respond_to? :tire
    # delete the index for the current model
    klass.tire.index.delete

    # the mapping definition must get executed again. for that, we reload the model class.
    load File.expand_path("../../app/models/#{klass.name.downcase}.rb", __FILE__)

  end
end

可供替代的

另一种方法是设置一个不同的ElasticSearch实例,以便在另一个端口(比如1234)上进行测试.

Tire::Configuration.url "http://localhost:1234"

然后,在适当的位置(例如,您的测试启动),您可以使用以下命令删除ElasticSearch测试实例上的所有索引:

Tire::Configuration.client.delete(Tire::Configuration.url)

也许您仍然必须确保模型类的轮胎映射定义仍然被调用.

Ruby-on-rails相关问答推荐

关于关联 has_many 的多级/三重嵌套形式

CanCanCan、Pagy 和 Meil​​iSearch,如何组合这 3 个 gem?

URL 中的 Rails slugs - 使用 Active Record Model Post 的 Title 属性而不是 ID

插件和 Ruby gem 之间的区别?

Rails 将字符串与视图中的变量连接的最佳方法

向现有控制器添加操作(Ruby on Rails)

如何使用 Vim 插入 ERB 标签?

如何在 Rails 3 中使用 Capybara 单击具有相同文本的第二个链接?

rails 3,简单数组的Kaminari分页

Rails 4.1 Mailer 预览和设计自定义邮箱

Rails 3 中图像路径的完整 url

如何禁用 HTTP 严格传输安全性?

Rails HABTM - 正确删除关联

从 ActiveRecord 对象中提取两个属性的快捷方式?

如何在 Ruby 中搜索数组?

如何在两个字段上对 ruby​​/rails 进行排序?

按照给定 ID 数组的顺序按 ID 查找模型记录

rails 3,如何在 Settings.yml 文件中使用 ENV 配置变量?

Rails:您已经激活了 rake 10.3.1,但您的 Gemfile 需要 rake 10.2.2 (Gem::LoadError)

设置EDITOR或BUNDLER_EDITOR环境变量