RSpec:如何测试:是否在类double上调用new

时间:2017-04-22 15:16:09

标签: rspec

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

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

使用double,我想测试Journey类在运行:new时收到card.check_in消息,但我无法获得类双精度来执行此操作。如果我在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的引用是什么,更重要的是,如何使用RSpec成功测试是否在类double上调用:new

我看过this question,但是问题解决了问题,而没有测试是否在课堂上调用了:new

1 个答案:

答案 0 :(得分:2)

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

因此,请尝试删除":#34;

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

另外,在.as_stubbed_const来电后添​​加class_double

journey = class_double("Journey").as_stubbed_const

相关问题