如何解决如何编写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 举报,一经查实,本站将立刻删除。