rspec で Job のリトライをテストする

August 07, 2022

これは何?

SSIA

確認環境

$ bundle exec rspec --version
RSpec 3.11
  - rspec-core 3.11.0
  - rspec-expectations 3.11.0
  - rspec-mocks 3.11.1
  - rspec-rails 4.0.2
  - rspec-support 3.11.0

事前準備

rspec を生成します。

$ bundle exec rails g rspec:job Sample
      create  spec/jobs/sample_job_spec.rb

Job を生成します。

$ bundle exec rails g job Sample
      invoke  rspec
   identical    spec/jobs/sample_job_spec.rb
      create  app/jobs/sample_job.rb

検証

app/jobs/sample_job.rb

class SampleJob < ApplicationJob
  queue_as :default

  retry_on StandardError, attempts: 3 do |job, exception|
    puts 'End!!!'
  end

  def perform(*args)
    raise 'hoge'
  end
end

spec/jobs/sample_job_spec.rb

require 'rails_helper'

RSpec.describe SampleJob, type: :job do
  include ActiveJob::TestHelper

  example do
    assert_performed_jobs 3 do
      described_class.perform_later rescue nil
    end

    # ここでリトライ後の処理で、特定のメソッドが呼ばれているかなどのテストを追加します
  end
end

確認

$ bundle exec rspec
End!!!
.

Finished in 0.05614 seconds (files took 1.79 seconds to load)
1 example, 0 failures

SHARE

Profile picture

Written by tamesuu