如何使用Carrierwave + FactoryGirl测试上传

时间:2012-03-28 05:43:36

标签: unit-testing rspec2 factory-bot

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

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对象。我该如何解决这个错误?

感谢。

3 个答案:

答案 0 :(得分:9)

我在寻找同样的答案时遇到了你的问题。请检查一下:

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

祝你好运!

更新

所以这就是我一步一步将文件上传到我的factories.rb。

一个。由于我使用rspec,我在spec /和spec / fixtures /下的目录图像中创建了一个目录fixture,然后在那里放了一个example.jpg图像,这样路径就是Rails.root / spec / fixtures / images / example .jpg

B中。接下来,在我的factories.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服务器)

℃。现在应该工作正常。

如果您有更多问题,请与我们联系。我会尽力帮助:)

答案 1 :(得分:5)

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

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

答案 2 :(得分:2)

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

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