Question: ActiveJob could not find record in `test` environment


ActiveJob could not find record in `test` environment

Answers 2
Added at 2016-12-16 08:12

This issue only exists in test environment. Everything runs fine in development environment.

I am facing a strange issue after recently upgrading to Rails from Rails Everything was working fine before this upgrade.

In one of my models, I use ActiveJob to perform a task.

# webhook_invocation.rb

def schedule_invocation

def init
  remember_webhook # No DB changes
  init_errors_context # No DB changes
  flow_step_invocation.implementation = self!

  return unless calculate_expressions  # No DB changes
  calculated! # An AASM event, with no callbacks

and in WebhookRequestJob#perform, I retrieve the object using the ID supplied

# webhook_request_job.rb

def perform(webhook_invocation_id)
  invocation = WebhookInvocation.find_by(id: webhook_invocation_id)

The problem is that in the #perform, it cannot find the record (invocation becomes nil). I even tried putting p WebhookInvocation.all as the first line, but all it prints is an empty collection. On the other hand, if I try p WebhookInvocation.all in #schedule_invocation method, it properly prints out all the objects of WebhookInvocation.

There is no exception being raised, no lines of warnings either.

Edit 1:

I even tried passing the object directly to #perform_later i.e. WebhookRequestJob.perform_later(self), but the received object at #perform is nil.

Edit 2:

I noticed that there are some messages like Creating scope :fail. Overwriting existing method, caused by using AASM. I eliminated them by using create_scopes: false. But that still didn't solve the problem.

Answers to

ActiveJob could not find record in `test` environment

nr: #1 dodano: 2016-12-16 11:12

My guess from the info you supplied is that you have are calling the schedule_invocation method in a after_save or after_create callback. Since the callback is called, ActiveJob might start processing the job even before the object is actually persisted (before COMMIT is done). In this case your record will not show up in the database when job is processed and you will get an empty collection or nil.

To fix this change your callback to after_commit to make sure that the COMMIT action has happened before you queue the job.

nr: #2 dodano: 2016-12-17 07:12

It turns out that config.active_job.queue_adapter was set to :inline as default before Rails 5, but it is set to :async in Rails 5.

This made the specs to fail (don't know why). To resolve this, I put the following line in my config/environments/test.rb:

config.active_job.queue_adapter = :inline
Source Show
◀ Wstecz