我想为我的应用程序创建一些测试,但出现以下错误:
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
目的。我该如何解决这个错误?谢谢。
最佳答案
我在寻找相同答案时遇到了您的问题。请检查这个:
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/示例.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. 现在应该可以正常工作了。
如果您有更多问题,请告诉我。我会尽力提供帮助:)
关于unit-testing - 如何使用 Carrierwave + FactoryGirl 测试上传,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9901756/