如何在mocha中断言模拟块

Bra*_*rad 5 ruby unit-testing mocking mocha.js

这个例子是人为的,请不要把它作为我的代码逐字逐句.

我需要断言如下内容:

def mymethod
    Dir.chdir('/tmp') do
        `ls`
    end
end
Run Code Online (Sandbox Code Playgroud)

最后我想断言:

  1. 使用适当的参数调用Dir.chdir.
  2. `使用适当的参数调用

我开始......

Dir.expects(:chdir).with('/tmp')
Run Code Online (Sandbox Code Playgroud)

但之后我不知道如何调用传递给Dir.chdir的块.

Ric*_*ond 4

您需要使用摩卡产量方法。另外,为反引号方法编写期望也相当有趣。你需要做出这样的期望:

expects("`")
Run Code Online (Sandbox Code Playgroud)

但在什么物体上呢?您可能会想到KernelObject,但这实际上不起作用。

举个例子,给定这个模块:

module MyMethod
  def self.mymethod
    Dir.chdir('/tmp') do
      `ls`
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

我可以写一个这样的测试:

class MyMethodTest < Test::Unit::TestCase
  def test_my_method
    mock_block = mock
    mock_directory_contents = mock
    MyMethod.expects("`").with('ls').returns(mock_directory_contents)
    Dir.expects(:chdir).yields(mock_block).returns(mock_directory_contents)
    assert_equal mock_directory_contents, MyMethod.mymethod
  end
end
Run Code Online (Sandbox Code Playgroud)

部分技巧是找出期望在哪个对象上调用反引号方法。这取决于上下文 - 无论调用该方法时self是什么。这里是模块MyMethod,但根据您定义mymethod 的位置,它会有所不同。