写了一个 Reindex module 代码如下,功能就是在 ActiveRecord 对象 save 时,异步创建索引
module Reindex
def async_reindex
AsyncIndexJob.perform_later(self.class.to_s, self.id)
end
def self.included(base)
base.class_eval do
base.send :after_save ,:async_reindex
end
end
end
测试代码
require 'rails_helper'
RSpec.describe AsyncIndexJob, type: :job do
include ActiveJob::TestHelper
describe "AsyncIndexJob" do
it "should enqueue" do
group = Group.create(……)
expect(enqueued_jobs.size).to eq(1)
end
end
end
但是结果非常奇怪,queue 的 size 是 3,也就是 after_save 被调用了 3 次,为什么会这样呢?
Failures:
1) AsyncIndexJob AsyncIndexJob should enqueue
Failure/Error: expect(enqueued_jobs.size).to eq(1)
expected: 1
got: 3