Search code examples
ruby-on-railsrspecsidekiqrails-activejob

RSpec, ActiveJob, Sidekiq: Avoid jobs from being fired when testing another job?


I am testing the ParseProjectsJob which fires the PushProjectJob when it's done. I need to avoid this behaviour, here's what the ParseProjectsJob looks like:

Have in mind that I'm using Sidekiq::Testing.inline! in my parse_project_spec.rb.

# [...] = Omitted code.

[...]
class ParseProjectsJob < ActiveJob::Base
  [...]
  def perform
      [...]
      PushProjectJob.set(wait: to_wait.second).
        perform_later({:project => onvia_project, :budget_years => @project_budget_years})
      [...]
  end
  [...]
end
[...]

So I've tried in my parse_projects_job_spec.rb:

allow_any_instance_of(PushProjectJob).to receive('perform_later') { true }

Outputs: PushProjectJob does not implement #perform_later

Also tried:

allow_any_instance_of(PushProjectJob).to receive('perform') { true }

It passes but the job is fired anyway.

And at last I've tried:

allow_any_instance_of(PushProjectJob).to receive_message_chain('set.perform_later') { true }

Outputs: PushProjectJob does not implement #set

parse_projects_job_spec.rb:

require 'rails_helper'
require 'sidekiq/testing'
require 'fileutils'

RSpec.describe ParseProjectsJob, type: :job do
  Sidekiq::Testing.inline!

  let(:perform_job) {
    allow(PushProjectJob).to receive_message_chain('set.perform_later') { true }
    exitable { ParseProjectsJob.perform_later }
  }

  let(:download_valid_file) {
    FileUtils.cp 'spec/fixtures/projects_sheets/valid_file.xlsx',
      Rails.root.join('public', 'downloads', 'projects_sheet')
  }

  describe "#perform" do
    it "parse and push all projetcs inside a sheet" do
      download_valid_file
      perform_job
      expect(Job.projects_parse.with_success.last.
        actions.last.message).
        to eql('No more files to parse, the job is done.')
    end
  end
end

Solution

  • This will work:

    let(:perform_job) {
      interval = double
      allow(PushProjectJob).to receive('set') { interval }
      allow(interval).to receive(:perform_later) { true }
      exitable { ParseProjectsJob.perform_later }
    }