2

我的 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

4

2 回答 2

2

你可以简单地写:

file_handle = mock
file_handle.stubs(:write).with('some file content').once
File.stubs(:open).with('filename.zip', 'wb').yields(file_handle).once
于 2015-10-08T10:14:50.200 回答
-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

这篇文章对我帮助很大

于 2015-10-08T09:52:36.937 回答