2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

deliver_laterのテスト時に同期実行

Posted at

非同期実行するジョブをテストする際に、テスト結果を検証するために同期実行したい場合。
supportを作成して同期実行する設定を行う。

spec/rails_helper.rb
RSpec.configure do |config|
  ...
  config.include ActiveJob::TestHelper
  ...

  # deliver_later の同期実行。
  # system/modelテストが対象。
  %i(system model).each do |type|
    config.when_first_matching_example_defined(type: type) do
      require 'support/perform_enqueued_jobs'
    end
  end
end
spec/support/perform_enqueued_jobs.rb
RSpec.configure do |config|
  config.before(:each, :perform_enqueued_jobs) do |example|
    @old_perform_enqueued_jobs = queue_adapter.perform_enqueued_jobs
    @old_perform_enqueued_at_jobs = queue_adapter.perform_enqueued_at_jobs
    queue_adapter.perform_enqueued_jobs = true
    queue_adapter.perform_enqueued_at_jobs = true
  end
  config.after(:each, :perform_enqueued_jobs) do |example|
    queue_adapter.perform_enqueued_jobs = @old_perform_enqueued_jobs
    queue_adapter.perform_enqueued_at_jobs = @old_perform_enqueued_at_jobs
  end
end

使い方は以下。

spec/models/my_model_spec.rb
RSpec.describe MyModel, type: :model do
...
  describe 'when hogehoge', :perform_enqueued_jobs do
  ...
  end
end
spec/systems/system_spec.rb
RSpec.describe MyModel, type: :system do
...
  describe 'when hogehoge', :perform_enqueued_jobs do
  ...
  end
end

参考

2
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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?