Rails 3带有载波的测试夹具?

问题描述:

我正在从附件_fu升级到载波,因为附件_fu在rails 3中损坏了。

I'm working on upgrading from attachment_fu to carrierwave, since attachment_fu is broken in rails 3.

由于我们的测试无效,因此无法运行任何测试

None of the tests are able to run, because we have invalid fixtures that were using the syntax from attachment_fu for attachment files.

例如,我们有一个Post模型,其中有一个PostAttachment。以下是PostAttachment固定装置中的数据:

For example, we have a Post model that has one PostAttachment. Here's what the data in the PostAttachment fixture looks like:

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附件的过程。

attachment_file would have been picked up by attachment_fu, and it would have taken care of all the processing to create the attachment_fu attachment for the model.

是否可以在灯具中安装图像附件,而是使用CarrierWave?

Is there a way to have image attachments in the fixtures, but with using CarrierWave instead?

我设法使它起作用的唯一方法是使用专门用于测试的存储提供程序,而该存储提供程序实际上并未保存/读取文件。

The only way I've managed to get this to work is to use a storage provider specifically for testing that doesn't actually save/read files.

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

In your config/initializers/carrier_wave.rb Add a NullStorage class that implements the minimum interface for a storage provider.

# 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时添加一个子句测试环境,例如

Then when initializing CarrierWave add a clause for the test environment, e.g.,

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

这里是我完整的carrier_wave.rb的要点,以供参考。它还包括如何设置S3以便在暂存/生产环境中上载以及用于开发的本地存储中,以便您可以查看如何在上下文中配置CarrierWave。

Here is a gist of my complete carrier_wave.rb for reference. It also includes how to setup S3 for uploads in staging/production and local storage for development so you can see how to configure CarrierWave in context.

配置好CarrierWave之后,您可以只需将任何字符串放在夹具列中即可模拟上传的文件。

Once CarrierWave is configured you can simply put any string in the fixtures column to simulate an uploaded file.