【问题标题】:Rspec how to test a Sidekiq job?Rspec如何测试Sidekiq工作?
【发布时间】:2021-10-31 12:02:59
【问题描述】:

我有一个看起来像这样的 Sidekiq 工作:

class Arbitrary::MarkSold < ApplicationJob
  def perform(item_id)
    return if Rails.env.test?
    item = Item.find_by(item_id)
    item.sold = true
    item.save
  end
end

相应的 RSpec 测试如下所示:

Rspec.describe Arbitrary::MarkSold, type: :job do
  describe 'perform' do
    it 'runs' do
      expect(Arbitrary::Marksold).to receive(:perform).and_return(nil)
      MarkSold.new.perform(34)
    end
  end
end

当我尝试运行此测试时,我因以下错误而失败:

Arbitrary::MarkSold does not implement: perform`.

但是,我可以清楚地看到Arbitrary::MarkSold 有一个perform 方法。

我已经阅读了Method Stubs,但无法从中得出正面或反面,也无法弄清楚如何将其应用于这种情况。

我非常感谢任何指向文档的指针或链接,而不是我链接的文档。作为初学者,我发现 rspec 文档对初学者不太友好。提前谢谢!

Ruby 版本:2.4.9 导轨版本:5.1.7 RSpec 版本:3.7

【问题讨论】:

    标签: ruby-on-rails methods rspec sidekiq stub


    【解决方案1】:

    我使用have_enqueued_job 来测试作业是否入队,假设这是您要测试的内容。好像是这样的。

    https://relishapp.com/rspec/rspec-rails/docs/matchers/have-enqueued-job-matcher

    【讨论】:

    • 谢谢!我如何诱导这个测试失败?
    • 这行得通,但它并没有真正回答我的问题。我将编写一些其他测试,我希望能够更好地了解我的代码为什么不起作用。
    【解决方案2】:

    你正在做的事情有一些问题:

    expect(Arbitrary::Marksold).to receive(:perform).and_return(nil)
    

    在上面的 sn-p 中,您期望类 Arbitrary::Marksold 接收 perform,但您不期望 instance 应该接收 perform。这就是您收到 does not implement: perform 错误的原因。

    你可以(我没有测试它,所以你可能需要调整一件事或另一件事):

    marksold_spy = instance_spy(Arbitrary::Marksold)
    allow(Arbitrary::Marksold).to(receive(:new).and_return(marksold_spy))
    expect(marksold_spy).to(receive(:perform).and_return(nil))
    

    但上述方法不是我的做法。我会这样做的方式:

    class Arbitrary::MarkSold
      include Sidekiq::Worker
    
      def perform(item_id)
        item = Item.update(item_id, sold: true)
      end
    end
    

    我的测试:

    Rspec.describe Arbitrary::MarkSold, type: :job do
      describe 'perform' do
        it 'runs' do
          item = create(:item, sold: false)
          Sidekiq::Testing.inline! do
            described_class.perform_async(item.id)
          end
          expect(item.reload.sold).to be_truthy
        end
      end
    end
    

    要了解更多关于Sidekiq::Testing的信息,您可以访问this link

    【讨论】:

      猜你喜欢
      • 2019-01-16
      • 2015-03-10
      • 1970-01-01
      • 2013-03-21
      • 2017-02-11
      • 2016-02-26
      • 2014-10-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多