Skip to content

Commit 931e984

Browse files
committed
Test we execute ActiveJob jobs similarly to Rails
Specifically they are wrapped in a Rails.application.executor block that will clear all thread-unsafe/request persisted values in memory, like ActiveSupport::CurrentAttributes.
1 parent 24b75f5 commit 931e984

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed

spec/delayed/job_spec.rb

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -549,6 +549,38 @@ def create_job(opts = {})
549549
expect(job).to be_failed
550550
end
551551
end
552+
553+
describe 'handing off to ActiveJob' do
554+
around do |example|
555+
old_adapter = ActiveJob::Base.queue_adapter
556+
ActiveJob::Base.queue_adapter = :delayed
557+
558+
example.run
559+
ensure
560+
ActiveJob::Base.queue_adapter = old_adapter
561+
end
562+
563+
it 'runs everything under the same executor block' do
564+
# Ensure the current attributes are persisted in the job, but then reset in this process
565+
ActiveJobAttributesJob.results.clear
566+
ActiveJobAttributesJob::Current.user_id = 0xC0FFEE
567+
ActiveJobAttributesJob.perform_later
568+
ActiveJobAttributesJob::Current.clear_all
569+
570+
# In a rails app this is in ActiveJob's railtie, wrapping the execute in an around callback that
571+
# leans on the Rails executor to reset things in jobs. Fake it here with execute around callback
572+
# setup the same, and only clear CurrentAttributes directly.
573+
ActiveJob::Callbacks.singleton_class.set_callback(:execute, :around, prepend: true) do |_, inner|
574+
ActiveSupport::CurrentAttributes.clear_all
575+
inner.call
576+
end
577+
578+
worker.work_off
579+
580+
expect(ActiveJobAttributesJob::Current.user_id).to be_nil
581+
expect(ActiveJobAttributesJob.results).to eq([0xC0FFEE])
582+
end
583+
end
552584
end
553585

554586
describe 'failed jobs' do

spec/sample_jobs.rb

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,3 +115,26 @@ def enqueue(job)
115115
class ActiveJobJob < ActiveJob::Base # rubocop:disable Rails/ApplicationJob
116116
def perform; end
117117
end
118+
119+
class ActiveJobAttributesJob < ActiveJobJob
120+
class Current < ActiveSupport::CurrentAttributes
121+
attribute :user_id
122+
end
123+
124+
def self.results
125+
@results ||= []
126+
end
127+
128+
def serialize
129+
super.merge("user_id" => Current.user_id)
130+
end
131+
132+
def deserialize(job_data)
133+
super
134+
Current.user_id = job_data["user_id"]
135+
end
136+
137+
def perform
138+
self.class.results << Current.user_id
139+
end
140+
end

0 commit comments

Comments
 (0)