unit-testing - 如何使用 Carrierwave + FactoryGirl 测试上传

标签 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目的。我该如何解决这个错误?

谢谢。

最佳答案

我在寻找相同答案时遇到了您的问题。请检查这个:

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/

相关文章:

c - 如何测试C中函数调用的顺序?

matlab - 在子类中将设置函数与测试一起使用

ruby-on-rails - 分解您的 RSpec 测试

ruby-on-rails-3.1 - 如何在 Rails 3 中模拟/ stub 配置初始值设定项哈希

ruby-on-rails - 如何将 "config.include FactoryBot::Syntax::Methods"添加到 spec_helper.rb 中的 rspec 配置 block ?

ruby - 使用 Devise 的 Rails 5,使用 Rspec 测试 Controller (销毁操作)

java - 为什么 Intellij 单元测试 View 显示的运行时间比运行测试的实际挂钟时间短得多?

ios - 如何在 iOS 单元测试中公开私有(private)属性?

ruby - RSpec 模拟失败 "undefined method ` -' for nil:NilClass"

ruby-on-rails - 工厂女孩 : association problem testing model which has validates_presence_of accepts_nested_attributes_for