在RSpec instance_double上存放一个setter

nif*_*fty 4 ruby unit-testing rspec mocking

在RSpec单元测试中,我有一个模拟定义如下:

let(:point) { instance_double("Point", :to_coords => [3,2]) }
Run Code Online (Sandbox Code Playgroud)

在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
Run Code Online (Sandbox Code Playgroud)

这是我收到的错误消息:

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

nif*_*fty 16

得到它了!正确的语法如下所示:

allow(point).to receive(:coords=).and_return([4,2])
Run Code Online (Sandbox Code Playgroud)

stub方法显然已被弃用.