Active Storage FixtureSet
Fixture 是一种组织你要测试的数据的方式,简而言之,就是示例数据。
要详细了解 Fixture,请阅读 ActiveRecord::FixtureSet
文档。
YAML
与其他 Active Record 支持的模型类似,ActiveStorage::Attachment
和 ActiveStorage::Blob
记录继承自 ActiveRecord::Base
实例,因此可以用 Fixture 填充。
考虑一个假设的 Article
模型类、其相关的 Fixture 数据,以及相关 ActiveStorage::Attachment
和 ActiveStorage::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 关系完好无损。
方法
包含的模块
类公共方法
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"
) %>
源代码: 显示 | 在 GitHub 上
# 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) 链接
源代码: 显示 | 在 GitHub 上
# 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