Kle*_* S. 4 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)>'
Run Code Online (Sandbox Code Playgroud)
这个错误是因为我的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
Run Code Online (Sandbox Code Playgroud)
测试期望一个Attachment
对象,但我正在创建一个Rack::Test::UploadedFile
对象.我该如何解决这个错误?
谢谢.
我在寻找同样的答案时遇到了你的问题.请检查一下:
祝好运!
更新:
所以这就是我一步一步将文件上传到我的factories.rb.
A.因为我使用rspec,我在spec /和spec/fixtures /下创建了一个目录图像,然后在那里放了一个example.jpg图像,这样路径就是Rails.root/spec/fixtures/images /example.jpg
B.接下来,在我的workers.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
Run Code Online (Sandbox Code Playgroud)
(可选:如果在rspec中重新启动spork服务器)
C.现在应该工作正常.
如果您有更多问题,请告诉我.我会尽力帮助:)
这是我发现做我需要的方式.
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
Run Code Online (Sandbox Code Playgroud)