23

我有这段代码可以用 Rspec 测试 ActiveJob 和 ActionMailer 我不知道如何真正执行所有排队的作业

describe 'whatever' do
  include ActiveJob::TestHelper

  after do
    clear_enqueued_jobs
  end  

  it 'should email' do
    expect(enqueued_jobs.size).to eq(1)
  end
end
4

3 回答 3

26

这是我解决类似问题的方法:

# rails_helper.rb
RSpec.configure do |config|
  config.before :example, perform_enqueued: true do
    @old_perform_enqueued_jobs = ActiveJob::Base.queue_adapter.perform_enqueued_jobs
    @old_perform_enqueued_at_jobs = ActiveJob::Base.queue_adapter.perform_enqueued_at_jobs
    ActiveJob::Base.queue_adapter.perform_enqueued_jobs = true
    ActiveJob::Base.queue_adapter.perform_enqueued_at_jobs = true
  end

  config.after :example, perform_enqueued: true do
    ActiveJob::Base.queue_adapter.perform_enqueued_jobs = @old_perform_enqueued_jobs
    ActiveJob::Base.queue_adapter.perform_enqueued_at_jobs = @old_perform_enqueued_at_jobs
  end
end

然后在规格中我们可以使用:

it "should perform immediately", perform_enqueued: true do
  SomeJob.perform_later  
end
于 2015-04-30T12:10:08.380 回答
24

正确的测试方法是检查入队作业的数量,如您的示例中所示,然后分别测试每个作业。如果你想做集成测试,你可以试试 perform_enqueued_jobs 助手:

describe 'whatever' do
  include ActiveJob::TestHelper

  after do
    clear_enqueued_jobs
  end  

  it 'should email' do
    perform_enqueued_jobs do
      SomeClass.some_action
    end
  end

end

请参阅ActiveJob::TestHelper 文档

于 2015-01-10T14:07:55.047 回答
0

只是结合了所有最好的部分,+包括sidekiq:

规范/支持/perform_jobs.rb

require 'sidekiq/testing'

RSpec.configure do |config|
  Sidekiq::Testing.fake!

  config.around(:each, perform_jobs: true) do |example|
    Sidekiq::Testing.inline! do
      queue_adapter = ActiveJob::Base.queue_adapter
      old_perform_enqueued_jobs = queue_adapter.perform_enqueued_jobs
      old_perform_enqueued_at_jobs = queue_adapter.perform_enqueued_at_jobs
      queue_adapter.perform_enqueued_jobs = true
      queue_adapter.perform_enqueued_at_jobs = true
      example.run
    ensure
      queue_adapter.perform_enqueued_jobs = old_perform_enqueued_jobs
      queue_adapter.perform_enqueued_at_jobs = old_perform_enqueued_at_jobs
    end
  end

end

规格/some_spec.rb

it 'works', perform_jobs: true do
  ...
end
于 2021-02-09T23:57:12.697 回答