Rails 3测试夹具与carrierwave?

我正在努力从attachment_fu升级到carrierwave,因为attachment_fu在rails 3中被破坏了。

没有一个测试能够运行,因为我们有无效的灯具使用attachment_fu的语法来附件文件。

例如,我们有一个Post模型,它有一个PostAttachment。 以下是PostAttachment夹具中的数据:

a_image: post_id: 1 attachment_file: /test/files/test.png 

这是我得到的错误:

 ActiveRecord::StatementInvalid: PGError: ERROR: column "attachment_file" of relation "post_attachments" does not exist LINE 1: INSERT INTO "post_attachments" ("post_id", "attachment_file"... 

attachment_file将拾取attachment_file,它将处理为模型创建attachment_fu附件的所有处理。

有没有办法在灯具中有图像附件,但是使用CarrierWave代替?

我设法使其工作的唯一方法是使用专门用于测试但实际上不保存/读取文件的存储提供程序。

config/initializers/carrier_wave.rb添加一个NullStorage类,该类实现存储提供程序的最小接口。

 # NullStorage provider for CarrierWave for use in tests. Doesn't actually # upload or store files but allows test to pass as if files were stored and # the use of fixtures. class NullStorage attr_reader :uploader def initialize(uploader) @uploader = uploader end def identifier uploader.filename end def store!(_file) true end def retrieve!(_identifier) true end end 

然后在初始化CarrierWave时为测试环境添加一个子句,例如,

 if Rails.env.test? config.storage NullStorage end 

以下是我完整的carrier_wave.rb的要点,以供参考。 它还包括如何在暂存/生产和本地存储中为上载设置S3以进行开发,以便您可以了解如何在上下文中配置CarrierWave。

配置CarrierWave后,您只需将任何字符串放入灯具列即可模拟上传的文件。

尝试传递文件而不是String。

 a_image: post_id: 1 attachment_file: File.open(Rails.root.join("test/files/test.png")) 

这适用于我使用FactoryGirl

注意:感谢@dkobozev编辑

配置/初始化/ carrier_wave.rb

在Rails 4中

 # class NullStorage is defined here before the following block if Rails.env.test? CarrierWave.configure do |config| config.storage NullStorage end end 

&在灯具中:

 a_image: post_id: 1 attachment_file: <%= File.open(Rails.root.join("test/files/test.png")) %> 

为了能够使用已上传文件的灯具以及在测试中上传,我最近使用了CarrierWave。 我写了一篇关于我是怎么做的文章 。

我们刚刚将所有灯具一起移除,系统为每个测试播种这些文件。 问问自己……你在这里需要这些灯具吗? 不可能不是。 和固定装置不要爆炸! 所以我们只使用Model.create!( ... )和测试的特定数据