Rails 3测试夹具与carrierwave?

kei*_*ley 18 unit-testing ruby-on-rails fixtures ruby-on-rails-3 carrierwave

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

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

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

a_image:
  post_id: 1
  attachment_file: <%= Rails.root>/test/files/test.png
Run Code Online (Sandbox Code Playgroud)

这是我得到的错误:

ActiveRecord::StatementInvalid: PGError: ERROR:  column "attachment_file" of relation "post_attachments" does not exist
LINE 1: INSERT INTO "post_attachments" ("post_id", "attachment_file"...
Run Code Online (Sandbox Code Playgroud)

attachment_file 本来会被attachment_fu选中,它会处理为模型创建attachment_fu附件的所有处理.

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

Ger*_*haw 19

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

config/initializers/carrier_wave.rbAdd a 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
Run Code Online (Sandbox Code Playgroud)

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

if Rails.env.test?
    config.storage NullStorage
end
Run Code Online (Sandbox Code Playgroud)

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

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

  • 嗯,我很有希望,但是......当我在我的功能规范中访问带有表单字段的页面时,这仍然显示为"不是公认的存储提供商".有没有办法将NullStorage注册为公认的提供商? (2认同)

e3m*_*eus 9

尝试传递文件而不是String.

a_image:
    post_id: 1
    attachment_file: File.open(Rails.root.join("test/files/test.png"))
Run Code Online (Sandbox Code Playgroud)

这适用于我使用FactoryGirl

注意:感谢@dkobozev编辑

  • `File.open(Rails.root +"/ test/files/test.png")`对我不起作用.`File.open(Rails.root.join("test/files/test.png"))`的确如此. (4认同)
  • 这不适用于灯具.如果没有别的东西你将不得不逃避带有ERB标签的Ruby代码,但即使这样它也无法工作. (3认同)
  • 这对我来说在Rails 4.1中都不起作用,我最终做的是将文件分配给测试中各自的属性.不确定这种方法有什么问题,但通过...... (2认同)