Ruby 产生控制的方法的Rspec试验

Ruby 产生控制的方法的Rspec试验,ruby,testing,rspec,yield,Ruby,Testing,Rspec,Yield,我目前正在为已经编写的项目代码编写rspec测试。 我尝试测试的代码如下所示: def foo (ip, user) #[...] result = "" Net::SSH.start(ip, user) do |session| result = session.exec!('some_command_in_linux') end #[...] end 我试图实现的是通过SSH将结果的分配与远程命令的执行有效地分离,并将一个伪字符串分配

我目前正在为已经编写的项目代码编写rspec测试。 我尝试测试的代码如下所示:

def foo (ip, user)
    #[...]
    result = ""
    Net::SSH.start(ip, user) do |session|
        result = session.exec!('some_command_in_linux')
    end
    #[...]
end
我试图实现的是通过SSH将结果的分配与远程命令的执行有效地分离,并将一个伪字符串分配给结果变量

我读过关于收益匹配器的文章,但没有成功地将它们应用到我的场景中

更具体地说,我的想法是:

expect {|block| Net::SSH::start(ip, user, &block).to receive(ip, user, &block).and_return(sample_output)}

有什么想法吗?

如果您不需要实际运行该块,只需忽略它即可。它不会运行,但会被安全地忽略:

expect(Net::SSH).to receive(:start).with(ip, user).and_return(sample_output)
如果您确实希望运行块,请使用并_yield:

如果希望会话对象以某种方式运行,则可以期望它执行以下操作:

session = double(:session)
expect(Net::SSH).to receive(:start).with(ip, user).and_yield(session)
expect(session).to receive(:exec!).with('some_command_in_linux').and_return(sample_output)

注入会话并使用test-double来解耦testAwesome!我想我迷失在更复杂的事情中了,在通过一个论证的过程中。在哪种情况下,您应该将块作为参数传递给期望值?您不能将块作为期望值传递@steve
session = double(:session)
expect(Net::SSH).to receive(:start).with(ip, user).and_yield(session)
expect(session).to receive(:exec!).with('some_command_in_linux').and_return(sample_output)