How to test that ActiveJob is enqueued?

前端 未结 3 2015
难免孤独
难免孤独 2021-01-21 10:08

I have a create action that calls an ActiveJob if the record is successfully saved.

def create
  @object = Object.new(importer_params)
  respond_to do |format|
         


        
相关标签:
3条回答
  • 2021-01-21 10:14

    I've always looked at the size of ActiveJob::Base.queue_adapter.enqueued_jobs to test if a job was called. giving the code

    it 'does something' do
      expect {
        post :create, { object: valid_attributes }
      }.to change {
        ActiveJob::Base.queue_adapter.enqueued_jobs.count
      }.by 1
    end
    

    You should make sure that you are setting the enqueued_jobs to an empty array after each spec to avoid any unexpected behaviour. You can do this in the spec/rails_helper.rb

    0 讨论(0)
  • 2021-01-21 10:30

    In official docs here is have_enqueued_job matcher

    The have_enqueued_job (also aliased as enqueue_job) matcher is used to check if given ActiveJob job was enqueued.

    https://relishapp.com/rspec/rspec-rails/docs/matchers/have-enqueued-job-matcher

    0 讨论(0)
  • 2021-01-21 10:35

    If you need to check that your job has been enqueued several times, you can now do this:

    expect {
      3.times { HelloJob.perform_later }
    }.to have_enqueued_job(HelloJob).at_least(2).times
    
    0 讨论(0)
提交回复
热议问题