我的spec_helper.rb具有以下配置:
RSpec.configure do |config|
config.mock_with :mocha
# .. other configs
end
我想测试以下代码:
File.open('filename.zip', 'wb') do |file|
file.write('some file content')
end
所以这是我的规格:
file_handle = mock
file_handle.stubs(:write).with('some file content').once
File.stubs(:open).with('filename.zip', 'wb').returns(file_handle).once
但是输出显示没有调用
write
方法。输出如下:
MiniTest::Assertion: not all expectations were satisfied
unsatisfied expectations:
- expected exactly once, not yet invoked: #<Mock:0x7fdcdde109a8>.write('some file content')
satisfied expectations:
- expected exactly once, invoked once: File.open('filename.zip', 'wb')
那么,我是否正确地使用了
write
方法如果没有,是否有其他方法可以在do |obj| ..end
块中编写方法调用规范? 最佳答案
你可以简单地写下:
file_handle = mock
file_handle.stubs(:write).with('some file content').once
File.stubs(:open).with('filename.zip', 'wb').yields(file_handle).once
关于ruby-on-rails - 在Rails中使用Mocha在File.open内部 stub 写入方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33010459/