非同期実行するジョブをテストする際に、テスト結果を検証するために同期実行したい場合。
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