英文:
Rails: How to correctly execute an ActiveJob within a test using inline adapter?
问题
我有以下的测试代码:
require "test_helper"
class DisbursementGenerationTest < ActionDispatch::IntegrationTest
test "disburse test orders" do
puts "Performing job..."
Merchant.all.each do |merchant|
DisburseJob.perform_later(merchant)
end
puts "Job performed"
sleep 10
assert_equal 2, Disbursement.count
end
end
在 /config/environment/test.rb
文件中,我将 ActiveJob 的队列适配器设置为 :inline
:
Rails.application.configure do
config.active_job.queue_adapter = :inline
测试中的任务根本没有执行。我可以看到两个 puts
语句的输出,但是任务没有运行。我已经检查了预期的两个商家对象存在。在开发环境中,我使用 Sidekiq 作为任务后端,它可以在 Rails 控制台手动执行任务,并且也可以执行应用程序中的定时任务。
如何在测试中正确执行 ActiveJob?
我已经执行了这个测试,并期望任务运行两次(每个商家对象运行一次)。但是任务根本没有执行。
英文:
I have the following test:
require "test_helper"
class DisbursementGenerationTest < ActionDispatch::IntegrationTest
test "disburse test orders" do
puts "Performing job..."
Merchant.all.each do |merchant|
DisburseJob.perform_later(merchant)
end
puts "Job performed"
sleep 10
assert_equal 2, Disbursement.count
end
end
In the /config/environment/test.rb I set the ActiveJob queue adapter to inline:
Rails.application.configure do
config.active_job.queue_adapter = :inline
The Job in the test is not executed at all. I see output from both puts statements, but job is not running. I have checked there are 2 merchant objects as expected. In Dev environment I use sidekiq as a job backend and it executes jobs fine both from rails console manually and also scheduled jobs within an app.
How to correctly execute ActiveJob within a test?
I have executed the test and expected the job to run twice (once for each merchant object). The job has not executed at all.
答案1
得分: 3
为了进行测试,你应该将队列适配器设置为test
:
config.active_job.queue_adapter = :test
然后你可以使用perform_enqueued_jobs
来执行作业:
class DisbursementGenerationTest < ActionDispatch::IntegrationTest
test "disburse test orders" do
Merchant.all.each do |merchant|
DisburseJob.perform_later(merchant)
end
perform_enqueued_jobs
assert_equal 2, Disbursement.count
assert_performed_jobs 2
end
end
有关test helper和测试AJ一般的更多信息。
英文:
For testing, you should set the queue adapter to test
:
config.active_job.queue_adapter = :test
And then you can execute the jobs with the perform_enqueued_jobs
:
class DisbursementGenerationTest < ActionDispatch::IntegrationTest
test "disburse test orders" do
Merchant.all.each do |merchant|
DisburseJob.perform_later(merchant)
end
perform_enqueued_jobs
assert_equal 2, Disbursement.count
assert_performed_jobs 2
end
end
Further info about the test helper and testing AJ generally.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论