[英]Rails Minitest: ActiveStorage NoMethodError: undefined method `download'
我已經低於 model 與 ActiveStorage:
class PortfolioReport < ApplicationRecord
has_many_attached :pdf_upload
validates :pdf_upload, content_type: 'application/pdf'
end
現在我想測試 ActiveStorage 是否運行良好。 我定義了以下固定裝置:
# fixtures/active_storage/attachments.yml
pdf_upload:
name: pdf_upload
record: current (PortfolioReport)
blob: pdf_upload
我嘗試遵循此答案,但基於生成的令牌的文件位置不起作用(嘗試生成校驗和失敗 - Errno::ENOENT: No such file or directory @ rb_sysopen
)。 因此,我將示例 pdf 文件放入fixtures/files/sample.pdf
中。 我最終得到了以下 blob 文件:
# fixtures/active_storage/blobs.yml
pdf_upload_blob:
key: 1234
filename: sample.pdf
content_type: application/pdf
service_name: local
byte_size: <%= File.size(Rails.root.join('test', 'fixtures', 'files', 'sample.pdf')) %>
checksum: <%= Digest::MD5.file(Rails.root.join('test', 'fixtures', 'files', 'sample.pdf')).base64digest %>
為了測試它是否有效,我得到了以下 minitest model:
class PortfolioReportTest < ActiveSupport::TestCase
test 'pdf attached' do
pdf = portfolio_reports(:current).pdf_upload
assert pdf.attached?
assert_not_nil pdf.download
assert_equal 374, pdf.byte_size
end
end
但我收到一個錯誤:
Error:
PortfolioReportTest#test_pdf_attached:
NoMethodError: undefined method `download' for #<ActiveStorage::Attached::Many:0x00007fd5c5b87890>
test/models/portfolio_report_test.rb:16:in `block in <class:PortfolioReportTest>'
你有many
關系。
如果您希望只有一個附件,請使用has_one_attached:pdf_upload
。 如果您想要多個文件,我建議為關聯使用復數名稱: has_many_attached:pdf_uploads
。
然后,如果你使用many
關系,你必須告訴 ruby 你要下載哪個文件:
test 'pdf attached' do
uploads = portfolio_reports(:current).pdf_uploads
assert uploads.attached?
pdf = uploads.first
assert_not_nil pdf.download
assert_equal 374, pdf.byte_size
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.