这个例子是人为的,请不要将它逐字作为我的代码。
我需要断言如下内容:
def mymethod
Dir.chdir('/tmp') do
`ls`
end
end
最后,我想断言:
- 使用适当的参数调用 Dir.chdir。
- ` 使用适当的参数调用
我开始...
Dir.expects(:chdir).with('/tmp')
但在那之后我不确定如何调用传递给 Dir.chdir 的块。
这个例子是人为的,请不要将它逐字作为我的代码。
我需要断言如下内容:
def mymethod
Dir.chdir('/tmp') do
`ls`
end
end
最后,我想断言:
我开始...
Dir.expects(:chdir).with('/tmp')
但在那之后我不确定如何调用传递给 Dir.chdir 的块。
您需要使用 mocha yield方法。另外,为backtick方法写一个期望是相当有趣的。你需要做出这样的期望:
expects("`")
但在什么对象上?您可能会想到Kernel或Object,但这实际上不起作用。
例如,给定这个模块:
module MyMethod
def self.mymethod
Dir.chdir('/tmp') do
`ls`
end
end
end
我可以写一个这样的测试:
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
部分技巧是找出期望调用反引号方法的对象。这取决于上下文 -调用该方法时的self是什么。这里是模块MyMethod,但根据您定义mymethod的位置,它会有所不同。