CarrierWave存根请求错误“不允许上传应用程序/八位字节流文件”

时间:2018-06-14 15:40:56

标签: ruby-on-rails ruby amazon-s3 rspec

在Rails应用程序中,我正在为继承CarrierWave功能的上传方法编写RSpec测试。该方法本身查看用户上传图像的URL,下载并重新上传到S3。在测试中,最后一步上传到本地存储而不是S3。

我正在尝试使用存根请求修改此过程。当CarrierWave请求URL时,我拦截存根,告诉它返回本地文件。

那部分有效。

当CarrierWave尝试上传存根文件时出现错误。这是错误。

CarrierWave::IntegrityError: You are not allowed to upload application/octet-stream files

这是存根请求。

## rails_helper.rb

...

require 'spec_helper'
require 'rspec/rails'
require 'sidekiq/testing'
require 'capybara/rspec'
require 'webmock/rspec'

...

RSpec.configure do |config|

  ...

  config.before(:each) do |example|
    body_file = File.open(File.expand_path('./spec/fixtures/files/1976.png'))
    stub_request(:get, /fakeimagehost.com/).to_return(status: 200, body: body_file)

这是RSpec

...
context 'when uploaded image URL does not match AWS URL' do
  let(:image) { build(:user_uploaded_image) }
  let(:image_file) { 'spec/fixtures/files/1976.png' }
  let(:html_string) { "<img src='http://fakeimagehost.com/image.png'" }
  let(:upload_foreign_image_service) { UploadForeignImageService.new(html_string) }

  it 'returns an array of uploaded images' do
    expect(upload_foreign_image_service.upload_images).to eql([image])
  end
end
...

以下是上传方法的相关部分。

...    
@uploaded_images = []

def upload_images
  parsed_html = Nokogiri::HTML.fragment(@original_html)
  parsed_html.css('img').each do |element|
    source = element.attributes['src'].value
    if source.match ...
      ...
      @uploaded_images |= [existing_image] if existing_image.present?
    else
      new_image = UserUploadedImage.new
      #### BLOWS UP HERE  ####
      new_image.embedded_image.download! source

      ...

    end
  end
  @uploaded_images
end

也很高兴提供UserUploadedImage课程。

1 个答案:

答案 0 :(得分:0)

这解决了这个问题。在存根请求的.to_return部分中,我需要指定文件类型。

stub_request(:get, /fakeimagehost.com/).to_return(status: 200, body: body_file, headers: {'Content-Type' =>'image/png'}

headers: {'Content-Type' =>'image/png'}是缺失的部分。