适用于特定作业的 ActiveJob 内联队列适配器

Joh*_*ash 1 ruby ruby-on-rails rails-activejob

有没有办法将 ActiveJob 队列适配器设置为内联特定后台作业?

就我而言,我想在测试中运行一些后台作业来构建集成测试。我不关心作业内部细节,因为我的目的只是运行后台作业并断言结果。但是,这些集成测试并未涵盖所有后台作业,因此我不想全局设置队列适配器。

Hir*_*103 6

您可以使用 RSpec 的 around_hook 功能:

module WithQueueAdapter
  def with_queue_adapter(new_adapter)
    around do |example|
      begin
        old_adapter = ActiveJob::Base.queue_adapter
        ActiveJob::Base.queue_adapter = new_adapter
        example.run
      ensure
        ActiveJob::Base.queue_adapter = old_adapter
      end
    end
  end
end


RSpec.configure do |config|
  config.extend WithQueueAdapter
end
Run Code Online (Sandbox Code Playgroud)

在你的测试中

describe "My cool feature" do
  with_queue_adapter :inline

  # examples go there
end
Run Code Online (Sandbox Code Playgroud)