【问题标题】:rspec: how to test ssh.scprspec:如何测试 ssh.scp
【发布时间】:2015-03-24 16:01:32
【问题描述】:

我正在尝试使用 rspec 测试以下 ruby​​ 代码。

begin
Net::SSH.start(server_ip, server_username, :password => server_password) do |ssh|
    ssh.scp.upload!(local_file, remote_file)
    ssh.exec!("some command")
    ... more ssh.exec!
end
rescue
    puts "Failed to SSH"
end

我的 rspec 看起来像:

ssh_mock = double

expect(SSH).to receive(:start).and_yield(ssh_mock)
expect(ssh_mock).to receive(:scp)
expect(ssh_mock).to receive(:exec!).with("some command")

问题是测试永远不会通过,因为它在到达 scp 时会跳转到救援,并且 scp.upload 从未正确测试过。

那么,有没有一种方法可以测试 scp.upload 的调用方式,类似于本例?

到目前为止,我能够测试 SCP 的唯一方法是使用单独的块。经验

Net::SCP.start(server_ip, server_username, :password => server_password) do |scp|
    scp.upload!(local_file, remote_file)
end

但是我可以像第一个示例一样测试它而无需将 SCP 与 SSH 分开吗?

【问题讨论】:

    标签: ruby rspec net-ssh


    【解决方案1】:

    我相信您还应该模拟从ssh.scp 返回的scp,如下所示:

    ssh_mock = double
    scp_mock = double('scp')
    
    expect(SSH).to receive(:start).and_yield(ssh_mock)
    expect(ssh_mock).to receive(:scp).and_return(scp_mock)
    expect(scp_mock).to receive(:upload!).with(local_file, remote_file)
    expect(ssh_mock).to receive(:exec!).with("some command")
    

    【讨论】:

    • 完美运行!谢谢。
    猜你喜欢
    • 2019-03-09
    • 1970-01-01
    • 1970-01-01
    • 2015-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-30
    相关资源
    最近更新 更多