按照有关测试的rails指南,对具有附件的两个类进行以下操作(使用法语命名变体,与保留的“文件”足够接近)
class Picture < ApplicationRecord
has_one_attached :fichier do |attachable|
attachable.variant :thumb, resize_to_limit: [100, 100]
attachable.variant :small, resize_to_limit: [250, 250]
end
[...]
class Document < ApplicationRecord
has_one_attached :fichier
控制器测试采用相同的模式进行,如下(对于每个类):
post pictures_url, params: { picture: { fichier: file_fixture_upload("space_chen.jpg", "image/jpg"), individual: individuals(:one), shop_id: shops(:one).id, individual_id: individuals(:one).id } }, xhr: true
[...]
post documents_url, params: { document: { fichier: file_fixture_upload("find_shipment.pdf", "application/pdf"), title: 'title', shop_id: shops(:one).id, individual_id: individuals(:one).id } }, xhr: true
storage.yml 配置遵循规定:
test_fixtures:
service: Disk
root: <%= Rails.root.join("tmp/storage_fixtures") %>
出于安全考虑,
space_chen.jpg
和find_shipment.pdf
文件已添加到fixtures/files目录中。
fixtures/active_storage/attachments.yml
一组灯具是其中一个命名约定对于读者来说是不透明的
document_fichier:
name: find_shipment
record: fichier (Document)
blob: fichier_find_shipment_blob
picture_fichier:
name: space_chen
record: fichier (Picture)
blob: fichier_space_chen_blob
同时
fixtures/active_storage/blobs.yml
fichier_find_shipment_blob: <%= ActiveStorage::FixtureSet.blob filename: "find_shipment.pdf", service_name: "test_fixtures" %>
fichier_space_chen_blob: <%= ActiveStorage::FixtureSet.blob filename: "space_chen.jpg", service_name: "test_fixtures" %>
在启动任一类的控制器测试时,总是出现以下错误:
NoMethodError: undefined method `file_fixture_upload' for #<PicturesControllerTest:0x000000010ca46278>
[...]
NoMethodError: undefined method `file_fixture_upload' for #<DocumentsControllerTest:0x00000001082dac90>
文档一开始就指出:
test "can sign up" do
post signup_path, params: {
name: "David",
avatar: file_fixture_upload("david.png", "image/png")
}
有什么问题吗?
如果使用
fixture_file_upload
代替 file_fixture_upload
可以吗?
post api_v1_create_business_card_path, params: {
front_image: fixture_file_upload('business-card.jpg', 'image/jpg'),
back_image: fixture_file_upload('business-card.jpg', 'image/jpg'),
language_hints: %w[en ja fr]
},
Rails 版本:7.0.8