How to test upload with Carrierwave + FactoryGirl

為{幸葍}努か 提交于 2019-12-23 15:30:01

问题


I want to create some tests for my app and I have the following error:

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)>'

This error is because I have this on my factories.rb file

  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

The test expect an Attachment object but I m creating an Rack::Test::UploadedFile object. How can I solve this error?

Thanks.


回答1:


I ran into your question while looking for the same answer. Please check this:

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

good luck!

update:

So here is what I did step by step to upload a file into my factories.rb.

A. Since I use rspec, I created a directory fixtures under spec/ and a directory images under spec/fixtures/, and then put an example.jpg image in there, such that the path was Rails.root/spec/fixtures/images/example.jpg

B. Next, in my factories.rb, I changed my definition as followed:

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

(optional: restart your spork server if in rspec)

C. Should work fine now.

Let me know if you have more issues. I'll do my best to help :)




回答2:


This is the way I found to do what I need.

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



回答3:


Another way to do the same thing:

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


来源:https://stackoverflow.com/questions/9901756/how-to-test-upload-with-carrierwave-factorygirl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!