Active Storage FixtureSet
固定資料是一種用於測試您要測試的資料的方式;簡而言之,範例資料。
若要深入了解固定資料,請閱讀 ActiveRecord::FixtureSet
說明文件。
YAML
與其他 Active Record 所支援的模型一樣,ActiveStorage::Attachment
和 ActiveStorage::Blob
記錄繼承自 ActiveRecord::Base
個體,因此可由固定資料填入。
考慮一個假設的 Article
範例類別、其相關的固定資料,以及 ActiveStorage::Attachment
和 ActiveStorage::Blob
記錄的相關固定資料
# 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 會為每個固定資料分錄新增資料庫記錄,並確保 Active Storage 關係完好無缺。
方法
包含的模組
類別公用方法
blob(filename:, **attributes) 連結
產生 ActiveStorage::Blob
個體屬性的 YAML 編碼表示,會解析相對於 ActiveSupport::Testing::FileFixtures.file_fixture
所提目錄的檔案,並將檔案上傳到 服務
範例
# 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"
) %>
個體公用方法
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