【问题标题】:Use a double for an instance variable of an object in Rspec在 Rspec 中为对象的实例变量使用双精度
【发布时间】:2016-10-02 09:15:57
【问题描述】:

我是 Ruby 的新手,这是我在 stackoverflow 上的第一个问题,所以请耐心等待我,呵呵。

我正在努力通过使用双精度的 Rpec 测试。

我有一个类 Plane,它有一个 attr_reader :plane_number 来自其初始化方法 @plane_number = plane_number。 attr_reader :plane_number

Class Plane   
   def initialize
   @plane_number = plane_number   
   end
end

我在另一个类 Airport 中使用此变量来指代特定飞机,其飞机编号在字符串消息中。我的代码中的字符串示例是:

class Airport
  def confirms_landed(plane)
  "The plane #{plane.plane_number} has landed"
  end
end

我使用 let(:plane) {double :plane}
为平面实例创建了一个 Rspec 测试 但我不确定如何为变量 plane_number 使用双精度。

describe Airport do
let(:plane) {double :plane}
   it "confirms a plane has landed" do
   subject.confirms_landed(plane)
   expect(subject.confirms_landed(plane)).to eq("The plane #{plane.plane_number} has landed")
   end
end

代码工作正常并返回正确的字符串,其中包含飞机编号,但是测试失败,因为我没有为变量 plane_number 分配双精度(我收到此错误消息:双精度:飞机收到意外消息:plane_number带(无参数))

我确信这很容易解决,但我似乎找不到正确的答案。

【问题讨论】:

  • double :plane, plane_number: 10

标签: ruby rspec mocking double stub


【解决方案1】:

据我所知,您只是缺少双机上的飞机编号方法

class Airport
  def confirms_landed(plane)
    "The plane #{plane.plane_number} has landed"
  end
end

describe Airport do
  let(:plane) { double(:plane, plane_number: 56) }

  it "confirms a plane has landed" do
      expect(subject.confirms_landed(plane)).to eq("The plane 56 has landed")
  end
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-12
    • 1970-01-01
    • 1970-01-01
    • 2014-09-15
    相关资源
    最近更新 更多