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.
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.