18

我正在从attachment_fu升级到carrierwave,因为attachment_fu在导轨3中断了。Rails 3载波测试夹具?

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

例如,我们有一个Post模型,它有一个PostAttachment。这里是长什么样的附着后夹具的数据,如:

a_image: 
    post_id: 1 
    attachment_file: <%= Rails.root>/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_fu接走了,它会照顾所有处理为模型创建attachment_fu附件。

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

回答

8

尝试传递文件而不是字符串。

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

这工作我使用FactoryGirl

注意事项:编辑感谢@dkobozev

+3

'File.open(Rails.root + “/test/files/test.png”)'不适用于工作我。 'File.open(Rails.root.join(“test/files/test.png”))''。 – dkobozev

+0

我改变了它。非常感谢。 – e3matheus

+1

在当前版本的carrierwave上,这不适合我。我试过引用/转义/ ERBing上面的'File.open ...'调用。我也尝试过使用'Rack :: Test :: UploadedFile.new(Rails.root.join(“test/files/test.png”))',它在作为参数传递时起作用。 – Leo

19

我已经成功地得到这个工作的唯一方法是专门使用存储提供商测试不会实际保存/读取文件。

在您的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 

下面是参考一个gist of my complete carrier_wave.rb。它还包括如何在登台/制作中为上传设置S3以及如何在本地存储中进行开发,以便您了解如何在上下文中配置CarrierWave。

一旦配置了CarrierWave,您可以简单地将任何字符串放在灯具列中以模拟上传的文件。

+0

当我在工厂尝试使用文件arg时,出现'ArgumentError: 不是公认的存储提供程序错误。按照您的建议,转换为字符串可以使其工作!好极了!谢谢! – brookr

+2

嗯,我很有希望,但是...当我访问我的功能规格中的表单字段页面时,仍然显示为“不是公认的存储提供商”。有没有办法将NullStorage注册为公认的提供者? – brookr

+0

我不完全确定NullStorage的功能;但我有单元测试,可以通过电子邮件发送以前上传文件的附件 - 如何测试这些附件?我尝试了上述步骤,他们似乎没有帮助。谢谢。 – Gerry

1

为了能够使用已经上传文件以及在测试中上传的灯具,我最近在CarrierWave上玩了一下。我写了一个article关于我该怎么做。

+0

文件不会永久保存,但测试也不会传递给我。 – Zhang

-4

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

2

config/initializers/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")) %>