我目前正在运行一个循环,其中retry在我的测试中执行。如何存根retry并仍然测试上面的代码?
我有一个片段可以捕获hostkeymatch异常:

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

最佳答案

对调用run-ssh-u命令的对象调用retry。
所以

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

关于ruby-on-rails - RSpec-处理救援块中的重试,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19362968/

10-10 13:13