4

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.

Kleber S.
  • 8,110
  • 6
  • 43
  • 69

3 Answers3

9

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

Community
  • 1
  • 1
sybohy
  • 1,856
  • 2
  • 20
  • 25
5

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
Kleber S.
  • 8,110
  • 6
  • 43
  • 69
  • wanted to point out to others that using the brackets `{}` shown in this answer, around the fixture_file_upload() call was what worked for me. without the brackets i was getting an error. – FireDragon Feb 04 '13 at 06:01
3

Another way to do the same thing:

factory :user do
  avatar File.open("#{Rails.root}/spec/fixtures/sample.jpg", 'r')
end
itsnikolay
  • 17,415
  • 4
  • 65
  • 64