2

我正在尝试编写一个测试,我需要由预期块创建的值来编写断言。

class Identification < ApplicationRecord
  include Wisper::Publisher

  after_save :publish_identification_declined

  private

  def publish_identification_declined
    if status_previously_changed? && status == "declined"
      broadcast(:identification_declined, identification: self)
    end
  end
end

我试图做这样的事情,但不幸identification_a的是最终没有被设置。

require "rails_helper"

RSpec.describe Identification do
  it "publish event identification_declined" do
    identification_a = nil
    expect { identification_a = create(:identification, :declined, id: 1) }
      .to broadcast(:identification_declined, identification: identification_a)
  end
end

我也有一种感觉,这可能不是一个好主意。

另一种方法可能是使用instance_of匹配器,但我不知道如何检查它是否是正确的实例。

4

1 回答 1

-1

我认为您不应该测试私有函数,因为它们就像黑匣子一样,无论它如何工作,只要它按预期返回,显然有时是必要的,但在这种情况下,我认为该函数不应该是私有的.

如果要测试该函数是否被调用,可以使用receiverspec 函数。一些喜欢:

require "rails_helper"

RSpec.describe Identification do
  subject { described_class.new(identification: nil, :declined, id: 1) }

  it "updates the state after save(or the event that should runs)" do
    expect { subject }.to receive(:publish_identification_declined)
    subject.save
  end
end

您还可以查看文档

于 2020-05-25T17:36:08.573 回答