【问题标题】:How to test upload with Carrierwave + FactoryGirl如何使用 Carrierwave + FactoryGirl 测试上传
【发布时间】:2012-03-28 05:43:36
【问题描述】:

我想为我的应用创建一些测试,但出现以下错误:

1) User feeds ordering should order feeds by id desc
     Failure/Error: @post_1 = FactoryGirl.create(:post)
     ActiveRecord::AssociationTypeMismatch:
       Attachment(#87413420) expected, got Rack::Test::UploadedFile(#81956820)
     # ./spec/models/user_spec.rb:37:in `block (3 levels) in <top (required)>'

此错误是因为我的 factories.rb 文件中有此错误

  factory :post do
    title "Lorem Ipsum"
    description "Some random text goes here"
    price "500000"
    model "S 403"
    makes "Toyota"
    prefecture "Aichi-ken"
    contact_info "ryu ryusaki"
    year "2012"
    shaken_validation "dec/2014"
    attachments [ Rack::Test::UploadedFile.new(Rails.root.join("spec/fixtures/files/example.jpg"), "image/jpeg") ]
    #attachments [ File.open(Rails.root.join("spec/fixtures/files/example.jpg")) ]
  end

测试需要一个Attachment 对象,但我正在创建一个Rack::Test::UploadedFile 对象。我该如何解决这个错误?

谢谢。

【问题讨论】:

    标签: unit-testing rspec2 factory-bot


    【解决方案1】:

    我在寻找相同答案时遇到了您的问题。请检查:

    How Do I Use Factory Girl To Generate A Paperclip Attachment?

    祝你好运!

    更新:

    所以这是我一步一步将文件上传到我的 factory.rb 的操作。

    A.由于我使用rspec,所以我在spec/下创建了一个目录fixtures,在spec/fixtures/下创建了一个目录images,然后在其中放了一个example.jpg图像,这样路径就是Rails.root/spec/fixtures/images/example .jpg

    B.接下来,在我的 factory.rb 中,我将定义更改如下:

    Factory.define :image do |image|
      image.image  fixture_file_upload( Rails.root + 'spec/fixtures/images/example.jpg', "image/jpg")
      image.caption           "Some random caption"
    end
    

    (可选:如果在 rspec 中,则重新启动您的 spork 服务器)

    C.现在应该可以正常工作了。

    如果您还有其他问题,请告诉我。我会尽力帮忙的:)

    【讨论】:

    • 谢谢。我昨天找到了答案,只是忘了在这里更新我的帖子。所以我会接受你的回答是正确的。 :)
    • 太棒了!希望这对将来的某人有所帮助。
    • 我使用的是 Rails 4,fixture_file_upload 正在附加 Rails.root,所以我只需要 todo fixture_file_upload("example.csv")
    • undefined method fixture_file_upload' for #<:syntaxrunner:0x007f9f0893e898>` 在最近的 rails/carrierwave/factorybot 版本上
    【解决方案2】:

    这是我发现做我需要的方式。

    factory :attachment do
      file { fixture_file_upload(Rails.root.join(*%w[spec fixtures files example.jpg]), 'image/jpg') }
    end
    
    factory :post do
      title "Lorem Ipsum"
      description "Some random text goes here"
      price "500000"
      model "S 403"
      makes "Toyota"
      prefecture "Aichi-ken"
      status 'active'
      attachments { [ FactoryGirl.create(:attachment) ] }
    end
    

    【讨论】:

    • 想向其他人指出,使用方括号 {} 在此答案中显示,在 fixture_file_upload() 调用周围对我有用。没有括号我得到一个错误。
    【解决方案3】:

    做同样事情的另一种方法:

    factory :user do
      avatar File.open("#{Rails.root}/spec/fixtures/sample.jpg", 'r')
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-06
      • 1970-01-01
      相关资源
      最近更新 更多