我正在尝试编写一个测试,在该测试中我需要由期望的块创建的值来编写断言。
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
匹配器,但是我不知道如何检查它是否是正确的实例。
我认为您不应该测试私有函数,因为它们就像黑匣子一样,无论它如何工作,只要它按预期返回,就需要花费很多时间,但在那种情况下,我认为该函数不应该处于私有状态。
如果要测试是否调用了该函数,则可以使用receive
rspec函数。像:
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
您也可以看到the documentation