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 ?!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With