Rails [解决了。] 求大神解决下:Rspec test warrierwave 遇到 CarrierWave::FormNotMultipart

hw676018683 · November 08, 2014 · 3094 hits

错误如下:

CarrierWave::FormNotMultipart:
       You tried to assign a String or a Pathname to an uploader, for security reasons, this is not allowed.`
        If this is a file upload, please check that your upload form is multipart encoded

但是我在 factory 中已经这样设置了

main_img Rack::Test::UploadedFile.new(File.open(File.join(Rails.root, '/spec/support/picture.jpg')))

测试代码:

parameters = {
          name: product.name,
          category_id: product.category_id,
          main_img: product.main_img,
          property: properties.to_json,
          skucate: skucates.to_json,
          remember_token: @remember_token
        }
expect{ post "/admin/products", parameters }.to change(Product, :count).by(1)

最后我去打印了下 main_img 发送前后的值 post 前:

#<AvatarUploader:0xce0f8d8 @model=#<Product id: nil, name: "product-7", category_id: 4, main_img: nil, buy_limit: nil, created_at: nil, updated_at: nil, store_id: 1, quantity: 30, status: true, price: #<BigDecimal:cdae3f8,'0.3E4',9(27)>>, @mounted_as=:main_img, @cache_id="1415432463-11068-3745", @filename="picture.jpg", @original_filename="picture.jpg", @file=#<CarrierWave::SanitizedFile:0xce0dfc4 @file="/home/huangwei/shop/spec/support/uploads/tmp/1415432463-11068-3745/picture.jpg", @original_filename=nil, @content_type="text/plain">, @versions={}>

post 过去之后:

"/home/huangwei/shop/spec/support/uploads/tmp/1415432463-11068-3745/picture.jpg"

感觉问题就是出在这,但是我在 store_dir 下找到了上传的文件,说明他又上传上去。 无法理解,求解啊,已经花了 2 个小时了,还是没解决

最后发现参数 main_img 应该是一个 UploadedFile 对象,而 product.main_img 得到的是一个自己写的 AvatarUploader,把 product.main_img 改成 Rack::Test::UploadedFile.new(File.open(File.join(Rails.root, '/spec/support/picture.jpg'))),测试通过。初学者要解决一个问题还真是难

No Reply at the moment.
You need to Sign in before reply, if you don't have an account, please Sign up first.