How to Fix Rails 6.1 'Initialization autoloaded the constants' Warning Messages

Stefanni Brasil

One of our clients had the Rails 6.1.4 version in their Gemfile.

When running the specs, we noticed this warning message:

"DEPRECATION WARNING: Sending mail with DeliveryJob and Parameterized::DeliveryJob
is deprecated and will be removed in Rails 7.0. Please use MailDeliveryJob instead."

It was caused by the application’s configuration default still using the Rails 5.1 version, and loading the defaults prior to that version:

# config/application.rb
class Application < Rails::Application
  config.load_defaults 5.1 # <--- default values pointing to a previous version than the current one
end

Changing load_defaults to 6.1 fixed that warning. YAY!

But then, it generated a bunch of warning messages when booting the app:

"DEPRECATION WARNING: Initialization autoloaded the constants
[a_bunch_of_cron_jobs]

Being able to do this is deprecated. Autoloading during initialization
is going to be an error condition in future versions of Rails.
Reloading does not reboot the application, and therefore code executed
during initialization does not run again. So, if you reload
SomeImportantCron, for example, the expected changes won't be reflected
in that stale Module object."
To autoload safely at boot time, please wrap your code in a reloader
callback this way:
Rails.application.reloader.to_prepare do
  # Autoload classes and modules needed at boot time here.
end
That block runs when the application boots, and every time there is a
reload. For historical reasons, it may run twice, so it has to
be idempotent.

All of the classes listed in the warning message were Cron Jobs. That led us to investigate how they were being called 🕵️

FIX: Wrap the loading code inside a Rails.application.reloader.to_prepare block

The Cron Jobs were being initialized during boot time. What the message is saying is that, to set things up during boot, you need to wrap them in a to_prepare block, which runs on boot, and after each reload:

To autoload safely at boot time, please wrap your code in a reloader callback this way:
Rails.application.reloader.to_prepare do
  # Autoload classes and modules needed at boot time here.
end

In our case, the Cron Jobs were being autoloaded in the Sidekiq initializer file. That’s where we needed to load them with the to_prepare block:

Rails.application.reloader.to_prepare do
  Sidekiq::Cron::Job.load_from_hash! config_file
end

Voilà! Warning messages were fixed. Cheers to upgrades!