【问题标题】:RSpec: How to test whether :new is called on a class doubleRSpec:如何测试是否在类双精度上调用了:new
【发布时间】:2017-04-26 02:46:00
【问题描述】:

我想测试在运行某行代码时是否在某个类上调用了:new。我有以下内容:

class TravelCard
  def check_in(station)
    self.in_journey = true
    self.current_journey = Journey.new(station)
  end
end

使用双精度,我想测试 Journey 类在运行 card.check_in 时收到 :new 消息,但我无法让类双精度来执行此操作。如果我在 RSpec 中尝试以下操作

describe TravelCard do
  describe '#check_in' do    
    it 'creates a new journey' do
      journey = class_double("Journey")
      station = double(:station)
      expect(journey).to receive(:new).with(:station)
      card.check_in(station)
    end
  end
end

我明白了

 Failure/Error: expect(journey).to receive(:initialize).with(:station)

       (ClassDouble(Journey) (anonymous)).initialize(:station)
           expected: 1 time with arguments: (:station)
           received: 0 times

谁能解释对anonymous 的引用是什么,更重要的是,如何成功地测试:new 是否在使用RSpec 的类双精度上被调用?

我查看了this question,但提问者自己的问题在没有测试:new 是否已在某个类上被调用的情况下得到了解决。

【问题讨论】:

  • 只是为了确保 -- 在您的测试中,您调用的是 #touch_in 而不是 #check_in,对吗?
  • 对不起,好地方。我实际上是在打电话给#check_in。

标签: rspec


【解决方案1】:

您应该传递station 实例而不是符号。

所以试着去掉“:”

expect(journey).to receive(:new).with(station)

另外,在您的class_double 调用之后添加.as_stubbed_const

journey = class_double("Journey").as_stubbed_const

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-30
    • 1970-01-01
    • 2022-01-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多