跳至内容 跳至搜索

Active Storage FixtureSet

夹具是一种组织数据的方法,您想用这些数据进行测试;简而言之,就是示例数据。

要了解有关 fixtures 的更多信息,请阅读 ActiveRecord::FixtureSet 文档。

YAML

与其他基于 Active Record 的模型一样,ActiveStorage::AttachmentActiveStorage::Blob 记录继承自 ActiveRecord::Base 实例,因此可以由 fixtures 填充。

考虑一个假设的 Article 模型类,其相关的 fixture 数据,以及相关的 ActiveStorage::AttachmentActiveStorage::Blob 记录的 fixture 数据

# app/models/article.rb
class Article < ApplicationRecord
  has_one_attached :thumbnail
end

# fixtures/active_storage/blobs.yml
first_thumbnail_blob: <%= ActiveStorage::FixtureSet.blob filename: "first.png" %>

# fixtures/active_storage/attachments.yml
first_thumbnail_attachment:
  name: thumbnail
  record: first (Article)
  blob: first_thumbnail_blob

处理时,Active Record 将为每个 fixture 条目插入数据库记录,并确保 Active Storage 关系完整。

方法
B
P
包含的模块

类公共方法

blob(filename:, **attributes)

生成 ActiveStorage::Blob 实例属性的 YAML 编码表示,解析相对于 ActiveSupport::Testing::FileFixtures.file_fixture 中提到的目录的文件,并将文件上传到 Service

示例

# tests/fixtures/active_storage/blobs.yml
second_thumbnail_blob: <%= ActiveStorage::FixtureSet.blob(
  filename: "second.svg",
) %>

third_thumbnail_blob: <%= ActiveStorage::FixtureSet.blob(
  filename: "third.svg",
  content_type: "image/svg+xml",
  service_name: "public"
) %>
# File activestorage/lib/active_storage/fixture_set.rb, line 66
def self.blob(filename:, **attributes)
  new.prepare Blob.new(filename: filename, key: generate_unique_secure_token), **attributes
end

实例公共方法

prepare(instance, **attributes)

# File activestorage/lib/active_storage/fixture_set.rb, line 70
def prepare(instance, **attributes)
  io = file_fixture(instance.filename.to_s).open
  instance.unfurl(io)
  instance.assign_attributes(attributes)
  instance.upload_without_unfurling(io)

  instance.attributes.transform_values { |value| value.is_a?(Hash) ? value.to_json : value }.compact.to_json
end