【问题标题】:Rails Minitest: ActiveStorage NoMethodError: undefined method `download'Rails Minitest:ActiveStorage NoMethodError:未定义的方法“下载”
【发布时间】:2021-08-04 05:20:18
【问题描述】:

我有以下带有 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

我尝试关注this answer,但基于生成的令牌的文件位置不起作用(尝试生成校验和失败 - 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 模型:

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>'

【问题讨论】:

  • 您是否尝试过按照 Ruby 指南中的说明进行操作? edgeguides.rubyonrails.org/active_storage_overview.html#testing 另外,当您尝试访问直接在测试中而不是通过夹具上传的文件时会发生什么?这样你就可以隔离它是配置问题还是夹具问题(我假设它在开发中工作,所以我的钱是在它作为夹具问题上)。
  • @DrewJohnston 我这样做了,但我读到 RailsGuides 中描述的方法将在 Rails 6.2 中可用。我的应用程序使用 6.1

标签: ruby-on-rails minitest


【解决方案1】:

你有一个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

【讨论】:

  • 好的,现在我收到一个错误:PortfolioReportTest#test_pdf_attached: ActiveStorage::FileNotFoundError: ActiveStorage::FileNotFoundError
  • 我建议你检查这个答案stackoverflow.com/questions/50453596/…你的评论现在是一个不同的问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-09
  • 2018-06-16
  • 2015-06-30
  • 1970-01-01
  • 2021-09-24
  • 1970-01-01
相关资源
最近更新 更多