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

RSpec:如何测试是否对类double调用:new,rspec,Rspec,我想测试在运行某一行代码时是否对类调用:new。我有以下资料: class TravelCard def check_in(station) self.in_journey = true self.current_journey = Journey.new(station) end end 使用double,我想测试当卡运行时,旅程类是否收到:new消息。check_in运行,但我无法让类double执行此操作。如果我在RSpec中尝试以下操作 describe Tra

我想测试在运行某一行代码时是否对类调用
:new
。我有以下资料:

class TravelCard
  def check_in(station)
    self.in_journey = true
    self.current_journey = Journey.new(station)
  end
end
使用double,我想测试当
卡运行时,
旅程
类是否收到
:new
消息。check_in
运行,但我无法让类double执行此操作。如果我在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
我明白了

有谁能解释一下对
匿名的引用是什么,更重要的是,如何使用RSpec成功地测试类double上是否调用了
:new


我已经看过了,但是询问者自己的问题在没有测试是否在类上调用了new
的情况下得到了解决。

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

因此,请尝试删除“:”

expect(旅程)。接收(:新)。与(车站)

另外,在您的
class\u double
调用之后添加
.as\u stubbed\u const


travel=class\u-double(“旅程”)。作为stubbed\u-const

只是为了确保--在测试中,您调用的是
\touch\u-in
,而不是
\check\u-in
,它正确吗?对不起,好点。我实际上是在打电话“登记”。
 Failure/Error: expect(journey).to receive(:initialize).with(:station)

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