我有这个代码用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
答案 0 :(得分:21)
以下是我解决类似问题的方法:
# 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
答案 1 :(得分:13)
正确的测试方法是检查排队作业的数量,如示例所示,然后分别测试每个作业。如果您想进行集成测试,可以尝试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
答案 2 :(得分:0)
刚刚结合了所有最好的作品,+包括sidekiq:
spec/support/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
spec/some_spec.rb:
it 'works', perform_jobs: true do
...
end