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

时间:2015-10-08 08:27:41

标签: ruby-on-rails ruby rspec mocha

我的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块内编写方法调用规范?

2 个答案:

答案 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给了我很多帮助