Sergey Panov
Sergey Panov

Reputation: 61

Rails: How to correctly execute an ActiveJob within a test using inline adapter?

I have the following test:

require "test_helper"

class DisbursementGenerationTest < ActionDispatch::IntegrationTest
  test "disburse test orders" do
    puts "Performing job..."
    Merchant.all.each do |merchant|   
      DisburseJob.perform_later(merchant)      
    end
    puts "Job performed"
    sleep 10
    assert_equal 2, Disbursement.count
  end
end

In the /config/environment/test.rb I set the ActiveJob queue adapter to inline:

Rails.application.configure do
  config.active_job.queue_adapter = :inline

The Job in the test is not executed at all. I see output from both puts statements, but job is not running. I have checked there are 2 merchant objects as expected. In Dev environment I use sidekiq as a job backend and it executes jobs fine both from rails console manually and also scheduled jobs within an app.

How to correctly execute ActiveJob within a test?

I have executed the test and expected the job to run twice (once for each merchant object). The job has not executed at all.

Upvotes: 0

Views: 883

Answers (1)

David
David

Reputation: 445

For testing, you should set the queue adapter to test:

  config.active_job.queue_adapter = :test

And then you can execute the jobs with the perform_enqueued_jobs:

class DisbursementGenerationTest < ActionDispatch::IntegrationTest
  test "disburse test orders" do
    Merchant.all.each do |merchant|   
      DisburseJob.perform_later(merchant)      
    end

    perform_enqueued_jobs

    assert_equal 2, Disbursement.count
    assert_performed_jobs 2
  end
end

Further info about the test helper and testing AJ generally.

Upvotes: 3

Related Questions