Rspec Mocks:从方法调用中模拟/生成块

时间:2009-10-16 19:52:34

标签: lambda rspec mocking

我有这段代码:

Net::SSH.start(@server, @username, :password => @password) do |ssh|
            output = ssh.exec!(@command)
            @logger.info 'SSH output: '
            @logger.info output
        end

我可以使用像这样的RSpec模拟框架来模拟SSH.Start,告诉我我已经启动了SSH会话:

Net::SSH.should_receive(:start).with("server", "user", :password => "secret") do
            @started = true
        end

this tells me whether or not i've @started the ssh session. now I need to mock the ssh.exec! method, which is easy enough:

Net::SSH.should_receive(:exec!).with("command")...

但是如何产生/调用包含ssh.exec的块!方法调用,因为我已经模拟了SSH.start方法?我可以调用一些简单的方法来执行这个块,但我不知道它是什么,也找不到任何关于rspec模拟框架的真正好的解释/文档。

1 个答案:

答案 0 :(得分:19)

Net::SSH.should_receive(:start).with(
  "server", "user", :password => "secret").and_yield(
  "whatever value the block should yield")

不确定为什么需要设置@started,因为should_receive会验证方法是否已被调用。

相关问题