【问题标题】:RSpec, ActiveJob, Sidekiq: Avoid jobs from being fired when testing another job?RSpec、ActiveJob、Sidekiq:在测试其他工作时避免工作被解雇?
【发布时间】:2016-02-26 04:15:24
【问题描述】:

我正在测试 ParseProjectsJob,它会在完成后触发 PushProjectJob。我需要避免这种行为,这就是 ParseProjectsJob 的样子:

请记住,我正在使用 Sidekiq::Testing.inline!在我的 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
[...]

所以我在我的 parse_projects_job_spec.rb 中进行了尝试:

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

输出: PushProjectJob 未实现#perform_later

也试过了:

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

它通过了,但工作还是被解雇了。

最后我试过了:

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

输出:PushProjectJob 没有实现#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

【问题讨论】:

  • 每次测试后尽量清空队列
  • @SunnyK 对不起,我忘了说,我正在使用 Sidekiq::Testing.inline!在 parse_projects_job_spec.rb 中。我会更新问题。谢谢。

标签: ruby-on-rails rspec sidekiq rails-activejob


【解决方案1】:

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

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

【讨论】:

  • 测试通过但作业被解雇。我会更新这个问题,以更好地展示我是如何做到的。谢谢。
【解决方案2】:

这将起作用:

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

【讨论】:

    猜你喜欢
    • 2021-10-31
    • 2015-03-10
    • 2015-03-29
    • 1970-01-01
    • 2019-01-16
    • 1970-01-01
    • 2017-02-11
    • 1970-01-01
    • 2021-05-20
    相关资源
    最近更新 更多