RSpec 模拟 send_file returns 缺少错误模板

RSpec mocking send_file returns error template is missing

在我的一个控制器中,我有以下方法:

def show
  @icon = @product.icon
  raise ActiveRecord::RecordNotFound unless @icon.present?

  send_file File.join('public', @icon), type: 'image/png', filename: 'icon.png', x_sendfile: true
end

我正在尝试像这样测试方法:

it 'it renders the icon' do
  create(:product, icon: 'icon.png')
  icon = double('icon', content_type: 'image/png', filename: 'icon.png')
  allow_any_instance_of(described_class).to receive(:send_file).and_return(icon)
  get(:show, params: { product: 'test' })
  expect(response.header['Content-Type']).to eq('image/png')
  expect(response.header['Content-Disposition']).to eq("attachment; filename=\"icon.png\"")
end

所以我的想法是用 double 来模拟 send_file 的响应。

然而,我得到的错误是此方法缺少 show 模板...所以它似乎没有正确地模拟出我想要的响应...

如何根据我的测试得到 send_file 到 return 模拟图像?

我也试过:allow(controller).to receive(:render).and_return(icon) 但这只是结束 return 一个空字符串而不是模拟图像...

所以我想出的解决方案是将实际图像添加到规范中,然后在我们连接到public 文件夹,然后让 send_file 正常工作,因为它现在正在拍摄真实图像,如下所示:

it 'it renders the icon' do
  create(:product, icon: 'icon.png')
  allow(File).to receive(:join).and_return('./spec/support/images/example.png')
  get(:show, params: { short_code: 'abc123' })
  expect(response.header['Content-Type']).to eq('image/png')
  expect(response.header['Content-Disposition']).to eq('attachment; filename="icon.png"')
end