ruby-on-railsminitestrails-activejob

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?


Solution

  • 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.