ウェブサービスを作っています。

RSpec で Active Job のテストを書く

追記(2016/11/11 10:33):

この記事の内容は古くなっており、あまりおすすめしません。RSpec 公式の方法をお使い下さい。

追記ここまで


Rails 4.2.1 で確認しています。

Post#ping で、10 分後に PingJob をエンキューするというテストを書いてみます。


spec/rails_helper.rb

RSpec.configure do |config|
  config.include ActiveJob::TestHelper
  config.include ActiveSupport::Testing::TimeHelpers  # 時間関係のテスト (travel_to メソッド) で使用
  ...
end

app/jobs/ping_job.rb

class PingJob < ActiveJob::Base
  queue_as :default

  def perform(msg)
    # do something...
  end
end

app/models/post.rb

class Post < ActiveRecord::Base
  def ping
    PingJob.set(wait: 10.minutes).perform_later 'hello'
  end
end

spec/models/post_spec.rb

require 'rails_helper'

describe Post, '#ping' do
  before { @post = Post.new }

  it '10 分後に PingJob をエンキューする' do
    time = Time.current

    travel_to(time) do
      assertion = {
        job: PingJob,
        args: ['hello'],
        at: (time + 10.minutes).to_i,
      }
      assert_enqueued_with(assertion) { @post.ping }
    end
  end
end

参考