Skip to content

Commit 1f2d06a

Browse files
committed
add spec for application_job
- tests request_id manipulation around queues - tests attaching activejob_id and request_id to logs
1 parent baf555b commit 1f2d06a

1 file changed

Lines changed: 81 additions & 0 deletions

File tree

spec/jobs/application_job_spec.rb

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
require 'rails_helper'
2+
3+
class TestJob < ApplicationJob
4+
def perform(*args); end
5+
end
6+
7+
RSpec.describe ApplicationJob, type: :job do
8+
include ActiveJob::TestHelper
9+
10+
# # not sure if needed
11+
# around do |example|
12+
# original_log_level = Rails.logger.level
13+
# Rails.logger.level = :debug
14+
# example.run
15+
# Rails.logger.level = original_log_level
16+
# end
17+
18+
after do
19+
ActiveJob::Base.queue_adapter.enqueued_jobs.clear
20+
end
21+
22+
describe 'jobs with request_id' do
23+
let(:request_id) { SecureRandom.uuid }
24+
25+
context 'when Current.request_id is set' do
26+
before do
27+
Current.request_id = request_id
28+
end
29+
30+
it 'enqueues the job with the request_id' do
31+
expect do
32+
TestJob.perform_later('some_arg')
33+
end.to have_enqueued_job(TestJob).with('some_arg', { request_id: request_id })
34+
end
35+
36+
it 'sets @request_id and removes it from the arguments' do
37+
job = TestJob.new('some_arg', { request_id: request_id })
38+
perform_enqueued_jobs { job.perform_now }
39+
40+
expect(job.instance_variable_get(:@request_id)).to eq(request_id)
41+
expect(job.arguments).to eq(['some_arg'])
42+
end
43+
44+
it 'logs the activejob_id and request_id' do
45+
job = TestJob.new('some_arg', { request_id: request_id })
46+
allow(job.logger).to receive(:with_fields=)
47+
48+
perform_enqueued_jobs { job.perform_now }
49+
50+
expect(job.logger).to have_received(:with_fields=).with(hash_including(activejob_id: job.job_id, request_id: request_id))
51+
end
52+
end
53+
end
54+
55+
describe 'jobs without a request_id' do
56+
context 'when Current.request_id is not set' do
57+
it 'enqueues the job without a request_id' do
58+
expect do
59+
TestJob.perform_later('some_arg')
60+
end.to have_enqueued_job(TestJob).with('some_arg')
61+
end
62+
63+
it 'does not set @request_id if not provided' do
64+
job = TestJob.new('some_arg')
65+
perform_enqueued_jobs { job.perform_now }
66+
67+
expect(job.instance_variable_get(:@request_id)).to be_nil
68+
expect(job.arguments).to eq(['some_arg'])
69+
end
70+
71+
it 'logs the activejob_id without a request_id' do
72+
job = TestJob.new('some_arg')
73+
allow(job.logger).to receive(:with_fields=)
74+
75+
perform_enqueued_jobs { job.perform_now }
76+
77+
expect(job.logger).to have_received(:with_fields=).with(hash_including(activejob_id: job.job_id, request_id: nil))
78+
end
79+
end
80+
end
81+
end

0 commit comments

Comments
 (0)