ruby-on-rails 在rspec中使用ActiveJob执行挂起作业

woobm2wo  于 2023-02-17  发布在  Ruby
关注(0)|答案(4)|浏览(133)

我有这个代码来测试ActiveJob和ActionMailer与Rspec我不知道如何真正执行所有排队的作业

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
9rygscc1

9rygscc11#

正确的测试方法是像你的例子一样检查排队作业的数量,然后分别测试每个作业。如果你想做集成测试,你可以尝试perform_enqueued_jobs helper:

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

参见活动作业::测试助手文档

o75abkj4

o75abkj42#

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

# 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
hgncfbus

hgncfbus3#

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

规范/支持/执行作业.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

规格/某些规格rb

it 'works', perform_jobs: true do
  ...
end
jyztefdp

jyztefdp4#

我有一个:inline_jobs帮助器,当应用到测试时,它将执行排队作业并清除排队作业

module InlineJobHelpers
  def self.included(example_group)
    example_group.around(:each, :inline_jobs) do |example|
      perform_enqueued_jobs do
        example.run
      end
    ensure
      clear_enqueued_jobs
    end
  end
end

RSpec.configure do |config|
  config.include ActiveJob::TestHelper, :inline_jobs
  config.include InlineJobHelpers, :inline_jobs
end

相关问题