How to test downloads with Carrierwave + FactoryGirl

I want to create some tests for my application, 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 occurs because I have this in the 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 expects an Attachment object, but I create a Rack::Test::UploadedFile object. How can I solve this error?

Thanks.

+4
source share
3 answers

I ran into your question looking for the same answer. Check this:

How to use Factory Girl to create a portfolio clip app?

Good luck

update:

So, here is what I did step by step to upload the file to my .rb factories.

a. Since I use rspec, I created a catalog inventory under spec / and catalog images in spec / fixtures /, and then placed the example.jpg image there, so the path was Rails.root / spec / fixtures / images / example.jpg

Q. Then, in my .rb factories, I changed my definition as follows:

 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 now work fine.

Let me know if you have more problems. I will do my best to help :)

+9
source

This is exactly how 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 
+5
source

Another way to do the same:

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

Source: https://habr.com/ru/post/1403810/


All Articles