Skip to content

Commit 4dd2694

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 869c08a commit 4dd2694

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

spec/delayed/job_spec.rb

+30
Original file line numberDiff line numberDiff line change
@@ -549,6 +549,36 @@ 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 = ActiveJob::Base.queue_adapter, :delayed
556+
example.run
557+
ensure
558+
ActiveJob::Base.queue_adapter = old_adapter
559+
end
560+
561+
it 'runs everything under the same executor block' do
562+
ActiveJobAttributesJob.results.clear
563+
ActiveJobAttributesJob::Current.user_id = 0xC0FFEE
564+
ActiveJobAttributesJob.perform_later
565+
ActiveJobAttributesJob::Current.user_id = nil
566+
567+
# In a rails app this is in ActiveJob's railtie, wrapping the execute in an around callback that
568+
# leans on the Rails executor to reset things in jobs. Fake it here with execute around callback
569+
# setup the same, and only reset CurrentAttributes
570+
ActiveJob::Callbacks.singleton_class.set_callback(:execute, :around, prepend: true) do |_, inner|
571+
ActiveSupport::CurrentAttributes.clear_all
572+
inner.call
573+
ActiveSupport::CurrentAttributes.clear_all
574+
end
575+
576+
worker.work_off
577+
578+
expect(ActiveJobAttributesJob::Current.user_id).to be_nil
579+
expect(ActiveJobAttributesJob.results).to eq([0xC0FFEE])
580+
end
581+
end
552582
end
553583

554584
describe 'failed jobs' do

spec/sample_jobs.rb

+23
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)