在 File.open 中使用 Mocha 在 Rails 中存根写入方法

Stubbing write method inside File.open using Mocha in Rails

我的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 方法进行了 stub 处理?如果没有,是否有任何其他方法可以在 do |obj| ..end 块内编写方法调用规范?

不确定你的情况,但我认为它可以帮助你

我需要更改块内的行为 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对我帮助很大

你可以简单地写:

file_handle = mock
file_handle.stubs(:write).with('some file content').once
File.stubs(:open).with('filename.zip', 'wb').yields(file_handle).once