3

我目前正在进入一个循环,retry在我的测试中执行。我怎样才能存根retry并仍然测试上面的代码?

我有一个片段可以捕捉 HostKeyMismatch 异常:

rescue Net::SSH::HostKeyMismatch => e
  e.remember_host!
  retry
end

我的规格:

describe "rescues Net::SSH::HostKeyMismatch" do
  it "resyncs the ssh keys" do
    Net::SSH::HostKeyMismatch.any_instance.should_receive(:remember_host!).and_return(true)
    ssh_class.new.run_ssh_command { raise Net::SSH::HostKeyMismatch }
  end
end

我得到的错误:

   The message 'remember_host!' was received by #<Net::SSH::HostKeyMismatch: Net::SSH::HostKeyMismatch> but has already been received by Net::SSH::HostKeyMismatch

更新:

我能够通过在下面的建议答案中添加一个计数器来解决该问题:

describe "rescues Net::SSH::HostKeyMismatch" do
  it "resyncs the ssh keys" do
    exception = Net::SSH::HostKeyMismatch.new
    exception.should_receive(:remember_host!).and_return(true)
    count = 0
    ssh_class.new.run_ssh_command do
      count += 1
      raise exception unless count > 1
    end
  end
end
4

1 回答 1

4

对调用 run_ssh_command 的对象调用重试。

所以

describe "rescues Net::SSH::HostKeyMismatch" do
  it "resyncs the ssh keys" do
    ssh_instance = ssh_class.new

    Net::SSH::HostKeyMismatch.any_instance.should_receive(:remember_host!).and_return(true)
    ssh_instance.should_receive(:retry)

    ssh_instance.run_ssh_command { raise  Net::SSH::HostKeyMismatch}
  end
end
于 2013-10-14T14:53:19.827 回答