8fe485228c79cc8d2adb51db7f5e6e6f
2015/12/09 14:41:58 投稿
1

RailsのActiveJobのテストを少し書きやすくする

Rails の ActiveJob::QueueAdapters::TestAdapter を上書きして、テストを綺麗に書けるようにメソッドを付け足した。

テストコードのリファクタリングも大事。

それにしても簡単にメソッド増やせて、Ruby便利だなー monkey

参考

Before

# spec/models/user_spec.rb
describe 'User' do
  describe '#send_mails' do
    include ActiveJob::TestHelper

    before { clear_enqueued_jobs }

    it do
      User.create!

      user_job = enqueued_jobs.find { |x| x[:args][0] == 'UserMailer' && x[:args][1] == 'new_user' }
      admin_job = enqueued_jobs.find { |x| x[:args][0] == 'AdminMailer' && x[:args][1] == 'new_user' }
      expect(user_job).to be
      expect(admin_job).to be
    end
  end
end

After

# spec/support/active_job_findable.rb
module ActiveJobFindable
  def has_job?(job: nil, args: nil)
    jobs = self
    jobs = jobs.select { |x| x[:job] == job } if job
    jobs = jobs.select { |x| x[:args][0, args.size] == args } if args
    jobs.present?
  end
end

module ActiveJob
  module QueueAdapters
    class TestAdapter
      def enqueued_jobs
        @enqueued_jobs ||= [].extend(ActiveJobFindable)
      end
    end
  end
end

# spec/models/user_spec.rb
describe 'User' do
  describe '#send_mails' do
    include ActiveJob::TestHelper

    before { clear_enqueued_jobs }

    it do
      User.create!

      expect(enqueued_jobs).to have_job args: ['UserMailer', 'new_user']
      expect(enqueued_jobs).to have_job args: ['AdminMailer', 'new_user']
    end
  end
end

みんなのコメント