【问题标题】:Stub a setter on RSpec instance_double在 RSpec instance_double 上存根设置器
【发布时间】:2014-08-26 19:43:10
【问题描述】:

在 RSpec 单元测试中,我有一个这样定义的模拟:

let(:point) { instance_double("Point", :to_coords => [3,2]) }

在 Point 类中,我还有一个 setter,用于被测类(称为Robot)。我想存根该设置器以测试Robot#move。这是我到目前为止的错误代码:

describe "#move" do
  it "sets @x and @y one step forward in the direction the robot is facing" do
    point.stub(:coords=).and_return([4,2])
    robot.move
    expect(robot.position).to eq([4,2])
  end
end

这是我收到的错误消息:

Double "Point (instance)" received unexpected message :stub with (:coords=)

【问题讨论】:

    标签: ruby unit-testing rspec mocking


    【解决方案1】:

    知道了!正确的语法如下所示:

    allow(point).to receive(:coords=).and_return([4,2])
    

    stub 方法显然已被弃用。

    【讨论】:

      【解决方案2】:

      另一种选择是在 double 的定义中存根 setter 方法,如下所示:

      let(:point) { double("point", 'coords=' => [4,2]) }
      

      详情请见this github issue

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-03-11
        • 1970-01-01
        • 1970-01-01
        • 2023-03-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多