Dwi Prihandi
Dwi Prihandi

Reputation: 67

How can I test `perform_now` job in Rails

Recently on my current project, I noticed that on our integration test, there are many assert_enqueued_jobs 1 code are commented out, then I ask other developer about it, He told me that we've changed many ActiveJob perform_later call to perform_now for speed reason, and that assert_enqueued_jobs can't catch those performed now jobs.

I've tried using assert_performed_jobs also but didn't worked out.

Can anyone give me insight or suggestion to test it? or it just can't be testable?

Upvotes: 3

Views: 5050

Answers (2)

Lam Phan
Lam Phan

Reputation: 3811

I used a mock(spy) to verify that ActiveJob called :perform_now:

job_perform_spy = Minitest::Mock.new
job_perform_spy.expect :call, "return value", [arguments]

YourJobClass.stub :perform_now, job_perform_spy do
    # the code will trigger perform_now            
end

job_perform_spy.verify

Upvotes: 0

fbelanger
fbelanger

Reputation: 3578

Untestable? Never!

The assert_enqueded_jobs is not actually testing code, rather checking that something was actually enqueued to happen later. If something happens right away, why test that it was enqueued?

I would try to keep the queue and force jobs to be performed/cleared using other of the ActiveJob::TestHelpers. But to that's just me, it makes little difference.

https://apidock.com/rails/v4.2.1/ActiveJob/TestHelper/assert_enqueued_jobs

Say your job was to send some email, just call the ActiveJob#perform_now and check ActionMailer::Base.deliveries.count. At this point, the actual test will be very tailored to the job.

Could be creating a Notification and you might want to assert that Notification.count has changed, whatever.

The main thing is that instead of checking that the job was enqueued and end of story, we're looking for the desired outcome from that job running.

Upvotes: 3

Related Questions