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

时间:2019-03-28 18:04:51

标签: ruby rspec ruby-on-rails-5 tdd

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

这是我到目前为止所拥有的:

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

我希望第一个测试通过,第二个失败。但是,我的第一个测试失败了,而第二个测试却通过了。 我在做什么错了?

1 个答案:

答案 0 :(得分: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