如何确保集成测试中的后台作业 运行?

How to ensure background jobs run in integration tests?

我通过水豚进行了 运行 集成测试。它访问网页、创建对象并呈现结果。创建对象时,控制器将创建一些相关对象的多个作业排入队列。

当我 运行 我的集成测试时,我希望能够检查呈现的页面,就好像那些工作已经完成一样。两个明显的解决方案是:

  1. 将队列适配器设置为 :inline
  2. 创建对象后手动 execute/clear 排队作业。

对于 1),我尝试将 before(:each) 中的队列适配器设置为 :inline,但这不会更改适配器,它继续使用测试适配器(在我的test.rb 配置文件):

before(:each) { ActiveJob::Base.queue_adapter = :inline }
after(:each) { ActiveJob::Base.queue_adapter = :test }
it "should work" do
  puts ActiveJob::Base.queue_adapter
end

输出:#<ActiveJob::QueueAdapters::TestAdapter:0x007f93a1061ee0 @enqueued_jobs=[], @performed_jobs=[]>

对于 2),我不确定这是否真的可行。 ActiveJob::TestHelpers 提供 perform_enqueued_jobs,但此方法没有帮助,因为它似乎仅适用于传入块中明确引用的作业。

假设您正在使用 RSpec,使用 perform_enqueued_jobs 的最简单方法是使用 around 块。将它与元数据标签结合起来,你可以做类似

的事情
RSpec.configure do |config|
  config.include(RSpec::ActiveJob)

  # clean out the queue after each spec
  config.after(:each) do
    ActiveJob::Base.queue_adapter.enqueued_jobs = []
    ActiveJob::Base.queue_adapter.performed_jobs = []
  end

  config.around :each, perform_enqueued: true do |example|
    @old_perform_enqueued_jobs = ActiveJob::Base.queue_adapter.perform_enqueued_jobs
    ActiveJob::Base.queue_adapter.perform_enqueued_jobs = true
    example.run
    ActiveJob::Base.queue_adapter.perform_enqueued_jobs = @old_perform_enqueued_jobs
  end

  config.around :each, peform_enququed_at: true do |example|
    @old_perform_enqueued_at_jobs = ActiveJob::Base.queue_adapter.perform_enqueued_at_jobs
    ActiveJob::Base.queue_adapter.perform_enqueued_at_jobs = true
    example.run
    ActiveJob::Base.queue_adapter.perform_enqueued_at_jobs = @old_perform_enqueued_at_jobs
  end
end

注意:您需要在 config/environments/test.rb 中将 queue_adapter 指定为 :test 如果尚未设置

然后您可以在测试中指定 :perform_enqueued 元数据,指定的任何作业都将是 运行

it "should work", :perform_enqueued do
  # Jobs triggered in this test will be run
end