Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why my job are not performed during test?

here a small description of my code (simplified)

app/jobs/

class GenerateInvoiceJob < ActiveJob::Base
  queue_as :default

  def perform()
    Invoice.create
  end
end

app/models/

class Product < ActiveRecord::Base
  def buy
    GenerateInvoiceJob.perform_later
  end
end

spec/jobs

RSpec.describe AnotherJob, type: :job do

  context "with filter" do
    ...
  end
end

spec/models

RSpec.describe Product, type: :model do


    describe '#buy' do
      it "should generate invoice" do
        Product.create().buy

        expect(Invoice.all.size).to eq 1
      end
    end
end

with rails 4.2.11

when I run

rspec spec/models/product_spec.rb

then the test is ok (the job is performed)

when I run

rspec spec -e 'should generate invoice'

then the test fail cause the job is not performed

if I delete all test jobs from spec/jobs and then run

rspec spec -e 'should generate invoice'

then the test is ok (the job is performed)

I can't understand why having some tests for jobs prevents other jobs to perform ? Is there a solution for this?

with rails 5 and rails 6

whatever I do, the test always failed as the job is never performed ?

Aren't jobs performed anymore during tests since rails 5 ?

thanks for help

update 1 after first answer :

thanks a lot for your answer just to be sure I do correctly :

I added in environment/test.rb config.active_job.queue_adapter = :test

and in my spec/models/product_spec.rb

  RSpec.describe Product, type: :model do
    describe '#buy' do
      it "should generate invoice" do
        ActiveJob::Base.queue_adapter.perform_enqueued_jobs = true
        Product.create().buy

        expect(Invoice.all.size).to eq 1
      end
    end
  end

not sure I put

    ActiveJob::Base.queue_adapter.perform_enqueued_jobs = true

at the good place ?!

like image 830
user2016483 Avatar asked Aug 31 '25 02:08

user2016483


1 Answers

You need to set:

ActiveJob::Base.queue_adapter.perform_enqueued_jobs = true

However, using have_enqueued_job is a more common approach.

EDIT: There's even an easier way that slipped my mind:

ActiveJob::Base.queue_adapter = :inline
like image 173
phil pirozhkov Avatar answered Sep 02 '25 16:09

phil pirozhkov