如何测试DelayedJob是否从另一个类调用方法?

问题描述 投票:0回答:1

我正在设置规范以测试作业是否在某些条件下调用方法。

这是我到目前为止:

describe RandomJob do
  context "when payload[:type] = MyModel" do
    let!(:my_model) { create :my_model }
    let!(:payload)  { { type: "MyModel", id: my_model.id } }

    context "when Model exists" do
      it "calls MyModel.fire! with payload" do
        RandomJob.perform_now(payload)
        expect_any_instance_of(MyModel).to receive(:fire!).with(payload)
      end
    end

    context "when Model does not exist" do
      it "does not call MyModel.fire!" do
        RandomJob.perform_now(payload)
        expect_any_instance_of(MyModel).not_to receive(:fire!)
      end
    end
  end
end

只是为了确保我的测试方式有效。我设置这样的工作:

class RandomJob < ApplicationJob
  def perform(payload)
    @payload = payload

    fire_model!
  end

  private

  def fire_model!
    my_model&.fire! @payload
  end

  def my_model
    MyModel.find(@payload[:id])
  end
end

我期望第一次测试通过,第二次测试失败。但是,我的第一次测试失败而第二次测试失败。我究竟做错了什么?

ruby rspec ruby-on-rails-5 tdd
1个回答
2
投票

你必须在perform_now电话之前提出期望。

    context "when Model exists" do
      it "calls MyModel.fire! with payload" do
        expect_any_instance_of(MyModel).to receive(:fire!).with(payload)
        RandomJob.perform_now(payload)
      end
    end

    context "when Model does not exist" do
      it "does not call MyModel.fire!" do
        expect_any_instance_of(MyModel).not_to receive(:fire!)
        RandomJob.perform_now(payload)
      end
    end
© www.soinside.com 2019 - 2024. All rights reserved.