【问题标题】:Rspec Mocks: mock / yield the block from a method callRspec Mocks:从方法调用中模拟/产生块
【发布时间】:2009-10-16 19:52:34
【问题描述】:

我有这个代码:

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

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

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

这告诉我我是否已经@started ssh 会话。现在我需要模拟 ssh.exec!方法,很简单:

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

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

【问题讨论】:

    标签: lambda rspec mocking


    【解决方案1】:
    Net::SSH.should_receive(:start).with(
      "server", "user", :password => "secret").and_yield(
      "whatever value the block should yield")
    

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

    【讨论】:

    • 不知道 should_receive... 有没有关于这方面的好文档?我的 google-fu 让我失望了......还有 - 如果我不关心 yield 块的返回值怎么办?我只是希望它被执行,以便我可以在 ssh.exec 上调用 should_receive!方法。
    • 这就是should_receive 的意思:如果没有收到,测试将失败。就文档而言,RSpec Book 非常出色。我推荐它来学习使用 RSpec,以及学习 BDD。
    • 哦,你也许可以在没有参数的情况下调用#and_yield()
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-11
    • 1970-01-01
    • 2015-08-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多