如何使用rspec测试写入文件?

问题描述 投票:0回答:1

我有这样的功能代码:

      Dir.mkdir('config') unless File.exist?('config')
      File.open('config/brakeman.yml', 'wb') do |file|
        file.write(response.body)

如何测试file.write(response.body)这行?我试图像这样模拟和存根:

  allow(response).to receive(:body).and_return(body)
  allow(File).to receive(:open).with('config/brakeman.yml', 'wb') do |file|
    file.write(response.body)
  end
  expect(File).to receive(:open).with('config/brakeman.yml', 'wb')
  subject.create_config(response)
  expect(file).to receive(:write).with(body)
  expect(File.open('config/brakeman.yml')).to eq(body)
ruby rspec mocking stub
1个回答
0
投票

我认为测试标准库方法不是一个好主意。只需用

覆盖
allow(File).to receive(:open).with('config/brakeman.yml', 'wb') do |file|
  expect(file).to receive(:write).with(response.body)
end

我认为应该就足够了>

不要测试已经测试过的代码:)

© www.soinside.com 2019 - 2024. All rights reserved.