在RSpec instance_double上存放一个setter

时间:2014-07-06 00:39:47

标签: ruby unit-testing rspec mocking

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

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

在Point类中,我还有一个setter,它在被测试的类中使用(称为Robot)。我想将该setter存根以测试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=)

2 个答案:

答案 0 :(得分:14)

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

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

显然已弃用stub方法。

答案 1 :(得分:0)

另一个选择是在双精度定义中将setter方法存根,如:

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

有关详细信息,请参阅this github issue