我的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
块内编写方法调用规范?
答案 0 :(得分:2)
您可以简单地写一下:
file_handle = mock
file_handle.stubs(:write).with('some file content').once
File.stubs(:open).with('filename.zip', 'wb').yields(file_handle).once
答案 1 :(得分:-1)
不确定是你的情况,但我认为它可以帮到你
我需要更改块File.open(...) do ... end
我设法这样做了
origin_open = File.method(:open)
allow(File).to receive(:open) do |*args, &block|
if condition
# change behavior here
# for example change args
end
# call original method with modified args
origin_open.call(*args, &block)
end
这article给了我很多帮助