rspec rails测试:如何强制ActiveJob作业在某些测试中内联运行?

时间:2016-05-17 16:24:26

标签: ruby-on-rails ruby rspec rails-activejob

我希望我的后台作业能够内联运行某些标记测试。我可以通过使用perform_enqueued do包装测试来完成此操作,但我希望能够使用元数据标记它们,并且如果可能的话,它会自动发生。

我尝试过以下方法:

it "does everything in the job too", perform_enqueued: true do
end

config.around(:each) do |example|
  if example.metadata[:perform_enqueued]
    perform_enqueued_jobs do
      example.run
    end
  end
end

但会导致错误:

undefined method `perform_enqueued_jobs=' for ActiveJob::QueueAdapters::InlineAdapter:Class

2 个答案:

答案 0 :(得分:4)

您需要将测试适配器设置为ActiveJob::QueueAdapters::TestAdapter,以响应.perform_enqueued_jobs =。您可以在spec/rails_helper.rb文件上执行此操作:

ActiveJob::Base.queue_adapter = :test

答案 1 :(得分:0)

在您的spec/rails_helper.rb中:

RSpec.configure do |config|
  # ...
  config.include ActiveJob::TestHelper
end

或者在您的测试中:

context "when jobs are executed" do
  include ActiveJob::TestHelper

  # ...
end

然后在您的测试中:

perform_enqueued_jobs do
  example.run
end