简体   繁体   中英

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

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 }
}

您的最后一次尝试接近解决方案,只需将allow_any_instance_of更改为allow

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM