【问题标题】:Use object created inside RSpec expect block in assertion在断言中使用在 RSpec 期望块中创建的对象
【发布时间】:2020-05-25 16:55:54
【问题描述】:

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

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 匹配器,但我不知道如何检查它是否是正确的实例。

【问题讨论】:

    标签: ruby-on-rails ruby rspec wisper


    【解决方案1】:

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

    如果要测试函数是否被调用,可以使用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

    【讨论】:

    • 这与问题无关。
    猜你喜欢
    • 1970-01-01
    • 2018-12-12
    • 1970-01-01
    • 1970-01-01
    • 2017-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多