【问题标题】:RSpec: How to test init methodsRSpec:如何测试初始化​​方法
【发布时间】:2017-09-19 11:18:28
【问题描述】:

我想测试当我初始化一个类的新实例时是否调用了某个方法。在我的项目中,我有以下代码:

class Journey
  def initialize(entry_station)
    @journey_complete = false
    @entry_station = entry_station
    self.start_journey
  end

  def start_journey
    ...
  end
end

我想编写一个 RSpec 测试,检查 start_journey 在初始化时在所有新旅程实例上是否被调用。通常,为了检查一个方法是否运行,我expect 一个对象接收某个消息,然后运行我希望发送它的代码。例如

expect(journey).to receive(:start_journey)
Journey.new(station)

我不能在这里执行此操作,因为我要测试的旅程实例在我运行第二行的代码之前不存在。 RSpec 是否有解决方案来测试init 方法?

【问题讨论】:

    标签: rspec


    【解决方案1】:

    您正在寻找它:

    expect_any_instance_of(Journey).to receive(:start_journey)

    https://github.com/rspec/rspec-mocks#settings-mocks-or-stubs-on-any-instance-of-a-class

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-16
      • 1970-01-01
      • 2010-11-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多