首页 > 解决方案 > 测试 ActiveStorage 附件 (FileNotFound)

问题描述

我在测试 ActiveStorage 附件时遇到错误。代码是这样的:

class AssemblyTest < ActiveSupport::TestCase

  test 'Updating svg attachment should upload the updated file' do
    @assembly = Assembly.create(name: assemblies(:head_gasket).name,
                                image: 
    fixture_file_upload('files/track-bar.svg', 'image/svg+xml'))
    assert @assembly.image.attached?
    assert_not_empty @assembly.image.download
  end
end

Minitest::UnexpectedError: ActiveStorage::FileNotFoundError: ActiveStorage::FileNotFoundError调用 @assembly.image.download 时出现以下错误 。断言通过attached?了,但我不知道为什么文件下载失败。tmp/storage此外, ActiveStorage 配置为存储文件的目录中也没有显示任何内容。

标签: ruby-on-railsrails-activestorage

解决方案


在挖掘 ActiveStorage 代码时,我发现这个片段依赖于实际的数据库提交来执行文档上传(或保存到磁盘):

after_commit(on: %i[ create update ]) { attachment_changes.delete(name.to_s).try(:upload) }

如果您在测试环境中使用数据库事务,则不会存储文档。

要解决这个问题,您可以手动触发提交回调:

run_callbacks(:commit)

因此,在您的情况下,这可能有效:

class AssemblyTest < ActiveSupport::TestCase

  test 'Updating svg attachment should upload the updated file' do
    @assembly = Assembly.create(name: assemblies(:head_gasket).name,
                                image: 
    fixture_file_upload('files/track-bar.svg', 'image/svg+xml'))
    @assembly.run_callbacks(:commit) # Run commit callback to store on disk
    assert @assembly.image.attached?
    assert_not_empty @assembly.image.download
  end
end

推荐阅读