如何在摩卡中断言模拟块
这个例子是人为的,请不要将其逐字作为我的代码。
我需要断言如下:
def mymethod
Dir.chdir('/tmp') do
`ls`
end
end
最后我想断言:
- Dir.chdir 是通过适当的参数。
- 适当参数调用
` 使用我开始时使用的
Dir.expects(:chdir).with('/tmp')
...但之后我不确定如何调用传递给 Dir.chdir 的块。
This example is contrived, please don't take it verbatim as my code.
I have the need to assert something like the following:
def mymethod
Dir.chdir('/tmp') do
`ls`
end
end
In the end I want to assert that:
- Dir.chdir is invoked with the appropriate parameters.
- ` is invoked with the appropriate parameters
I started off with...
Dir.expects(:chdir).with('/tmp')
but after that I'm not sure how to invoke the block passed to Dir.chdir.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要使用摩卡 yields 方法。另外,为 backtick 方法编写一个期望是相当有趣的。你需要做出这样的期望:
但是在什么对象上呢?您可能会想到内核或对象,但这实际上不起作用。
举个例子,给定这个模块:
我可以编写这样的测试:
部分技巧是找出期望调用反引号方法的对象。这取决于上下文 - 无论调用该方法时 self 是什么。这里是模块 MyMethod,但根据您定义 mymethod 的位置,它会有所不同。
You need to use the mocha yields method. Also, writing an expectation for the backtick method is rather interesting. You need to make an expectation like this:
But on what object? You might think on Kernel or Object, but that doesn't actually work.
As an example, given this module:
I could write a test like this:
Part of the trick is to figure out which object to expect the backtick method to be invoked on. It depends on the context - whatever self is when that method is invoked. Here it is the module MyMethod, but depending on where you define mymethod it will be different.