LoginSignup
3
1

More than 3 years have passed since last update.

Rails6でActiveJobのQueueAdapterがTestAdapterに上書きされてしまい非同期で実行されてしまう

Last updated at Posted at 2020-03-17

Rails6の不具合でRAILS_ENV=testの場合、Railsのconfig.active_job.queue_adapterの設定に関わらずActiveJobが非同期で実行されてしまう不具合が発生しています。これは現在(2020/2/28)の6-0-stableでも修正されていません。

今回はrspec-rails & sidekiqを利用しているという前提で書きます。

原因

Rails側のバグです。active_job/railtie.rb を6-0-stableと5-2-stableで比較してみると、
active_job.set_configs initializerにコードが追加されています。

https://github.com/rails/rails/blob/5-2-stable/activejob/lib/active_job/railtie.rb
https://github.com/rails/rails/blob/6-0-stable/activejob/lib/active_job/railtie.rb

active_job/lib/active_job/railtie.rb
      ActiveSupport.on_load(:action_dispatch_integration_test) do
        include ActiveJob::TestHelper
      end

ここでincludeされているActiveJob::TestHelperが原因です。

ActiveJob::TestHelperのbefore_setupで queue_adapter_for_testにハードコードされている ActiveJob::QueueAdapters::TestAdapter というadapterに上書きされてしまっていることで発生していました。

activejob/lib/active_job/test_helper.rb
    def before_setup # :nodoc:
      test_adapter = queue_adapter_for_test

      queue_adapter_changed_jobs.each do |klass|
        klass.enable_test_adapter(test_adapter)
      end
# ...
# ...
# ...
    def queue_adapter_for_test
      ActiveJob::QueueAdapters::TestAdapter.new
    end

対策

別のissueにこんなコードで修正できるのでは?とありますが、issueに反応が無いので取り込まれる可能性は低いかもしれません。。。

Rails側の修正を待つという手もありますが、spec_helperに下記のコードを追加することで対応できます。

spec/spec_helper.rb
RSpec.configure do |config|
  config.before(:each) do
    (ActiveJob::Base.descendants << ActiveJob::Base).each(&:disable_test_adapter)
  end
end

これでRSpec & Sidekiqの環境でもTestAdapterの上書きをキャンセルできます。

issue

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1