Search code examples
ruby-on-railsrspecdelayed-job

Test that Delayed Job is called


I am trying to test that a part of my code is running a DelayedJob. Here's code:

def start_restream
  ...
  puts 'Here'
  Delayed::Job.enqueue(Restream::StartAllJob.new(channel.id))
  puts 'After'
  ...
end

#app/jobs/restream/start_all_job.rb
class Restream::StartAllJob < Struct.new(:channel_id)
  def perform
    puts "Inside"
    ...
  end
end

In my spec_helper.rb I have Delayed::Worker.delay_jobs = false. The spec:

it 'runs Delayed::Job::Restream::StartAll' do
  post :start_restream, :id => channel.id
  expect(Restream::StartAllJob).to receive(:new)
end

It prints out

Here
Inside
After

when running, so I know that it is called. But test fails:

Failure/Error: expect(Restream::StartAllJob).to receive(:new) 

(Restream::StartAllJob (class)).new(*(any args))
       expected: 1 time with any arguments
       received: 0 times with any arguments

Or, if I use expect_any_instance_of(Restream::StartAllJob).to receive(:perform) it says

Failure/Error: example.run
       Exactly one instance should have received the following message(s) but didn't: perform

What am I doing wrong and how can I test this?


Solution

  • It's just the mistake I made in the order: expect(Restream::StartAllJob).to receive(:new) should be written before post :start_restream, :id => channel.id