はじめに
retry_on
の attempts
オプションを使って何回リトライするかを指定することが出来ます。「ほんとうにリトライできている?」と指定した回数でリトライが出来ているかのテストについての記事です。
やったこと
パラメータの検証
retry_on
はクラスメソッドなので呼び出したときに期待する回数が検証できるかな?と思ったんですがクラスの中身がロードされた時点で評価されるので RSpec ではメソッド呼び出しのテストは失敗します だってもう呼び出し終わっているもの。
expect(GuestsCleanupJob).to receive(:retry_on).with(wait: 2.hours, attempts:3).exactly(3).times
retry_on
のブロックで指定した内容で検証する
retry_on
のブロックはジョブがリトライする度に実行するのではなく attempts
オプションで指定した回数が超えたときに評価するので今回の何回できたか?というのにはマッチしない。
class GuestsCleanupJob < ApplicationJob
retry_on LongWaitError do
# レコードをつくったりログを出力したり...
end
end
assert_performed_jobs
を使う
テストの中で例外を発生するようなスタブを作成する必要がありますが、assert_performed_jobs
で何回リトライしたかの回数を指定することで検証ができます。
RSpec.describe GuestsCleanupJob, type: :job do
example do
assert_performed_jobs 9 do
described_class.perform_later rescue nil
end
end
end
assert_performed_jobs
は内部で perform_enqueued_jobs
を呼んでいるのでブロックを指定せず次のようにも実行できます。
RSpec.describe GuestsCleanupJob, type: :job do
example do
perform_enqueued_jobs do
described_class.perform_later rescue nil
end
assert_performed_jobs 9
end
end