如何编写RSpec测试以确保Searchkick重新为记录编制索引?

如何解决如何编写RSpec测试以确保Searchkick重新为记录编制索引?

问题

我正在编写一个规范,以测试在创建关联的Image记录时是否对我的产品模型进行重新索引。

文档建议在测试中调用Product.search_index.refresh以确保索引是最新的,但这违反了目的,因为我想确保Image上的after_create钩子导致Product重新索引。 / p>

解决方案1:在测试中使用sleep

我可以打电话给sleep,直到Searchkick更新索引,但这会使我的测试变慢并使它们变脆。

product = create(:product)
Product.search_index.refresh

image_name = 'a_lovely_book.png'

search_results = Product.search image_name,fields: [:image_names]

# This passes.
expect(search_results.count).to eq(0)

image = create(:product_image,name: image_name)

# This causes the test to pass because it gives Searchkick time to reindex Product.
sleep 5

# This succeeds if I have the sleep call above.
search_results = Product.search image_name,fields: [:image_names]
expect(search_results.count).to eq(1)

解决方案2:是否在Rails.env.test上立即更新索引?

我也考虑过在Image类中做类似的事情,以便在测试中立即进行重新索引。但是我希望编写大量此类测试,而且我不想一遍又一遍地重复这段代码

class Image
  belongs_to :product
  after_create :reindex_product
  
  def reindex_product
    if Rails.env.test?
      product.search_index.refresh
    else
      product.reindex
    end
  end
end

解决方案3:使用间谍或模拟物

不确定我该怎么做,但是也许有一种方法可以使用间谍或模拟来确保reindex方法在Product上被调用

解决方法

我想确保我在Image上的after_create钩子导致产品重新编制索引。

您不是在测试重新索引编制,只是在适当的时间启动了重新编制索引。因此,模拟是必经之路。如果您认为有必要,请在其他地方测试实际的重新索引编制。

假设图片看起来像这样:

class Image < ApplicationRecord
  belongs_to :product

  # Note: the docs suggest after_commit so all saves will be reindexed.
  after_commit :reindex_product

  def reindex_product
    product.reindex
  end
end

RSpec中的测试看起来像...

describe '.create' do
  it 'reindexes the product' do
    expect(product).to receive(:reindex)

    Image.create( product: product,... )
  end
end

# This test illustrates why after_create might be insufficient.
describe '#save' do
  it 'reindexes the product' do
    expect(product).to receive(:reindex)

    image = Image.new( product: product,... )
    image.save!
  end
end

或者,如果您使用的是asynchronous reindexing,则需要检查重新索引作业是否已排队。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?
Java在半透明框架/面板/组件上重新绘画。
Java“ Class.forName()”和“ Class.forName()。newInstance()”之间有什么区别?
在此环境中不提供编译器。也许是在JRE而不是JDK上运行?
Java用相同的方法在一个类中实现两个接口。哪种接口方法被覆盖?
Java 什么是Runtime.getRuntime()。totalMemory()和freeMemory()?
java.library.path中的java.lang.UnsatisfiedLinkError否*****。dll
JavaFX“位置是必需的。” 即使在同一包装中
Java 导入两个具有相同名称的类。怎么处理?
Java 是否应该在HttpServletResponse.getOutputStream()/。getWriter()上调用.close()?
Java RegEx元字符(。)和普通点?