You need to enable JavaScript to run this app. Rspec测试中FactoryBot挂载ActiveStorage附件报IntegrityError
优惠活动
大模型
产品
解决方案
定价
更多

Rspec测试中FactoryBot挂载ActiveStorage附件报IntegrityError

Rails 6 ActiveStorage 出现 ActiveStorage::IntegrityError 解决方案

问题场景

  • 工厂调用方式为:
    @loan_migration = create(:migration_session, :loan, cooperative: @cooperative, management: @manager)
    
  • 工厂定义如下:
    FactoryBot.define do
      factory :migration_session, class: Migration::Session do
        cooperative
        management
        trait :loan do
          excel_file { Rack::Test::UploadedFile.new("#{Rails.root}/public/payment_migration.xlsx", 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') }
        end
      end
    end
    
  • 模型定义为:
    class Migration::Session < ApplicationRecord
      self.table_name = "migration_sessions"
      has_one_attached :excel_file
    end
    
  • 实例保存时触发报错,报错栈指向activestorage-6.0.3.4的DiskServiceensure_integrity_of方法,核心报错为:
    ActiveStorage::IntegrityError
    

报错原因

该错误为ActiveStorage文件完整性校验失败:上传到磁盘存储的文件内容,与计算Blob校验和时使用的原文件内容不一致,触发校验拦截。常见诱因是文件指针偏移、二进制文件被意外编码转换。

解决步骤

  1. 修改工厂文件赋值逻辑(优先采用)
    替换原trait中的Rack::Test::UploadedFile初始化逻辑,避免文件指针偏移、路径拼接编码、二进制文件换行符转换问题:

    trait :loan do
      excel_file do
        file_path = Rails.root.join('public', 'payment_migration.xlsx')
        # 以二进制只读模式读取文件内容到内存流
        content = File.read(file_path, mode: 'rb')
        io = StringIO.new(content)
        Rack::Test::UploadedFile.new(
          io,
          'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
          original_filename: 'payment_migration.xlsx'
        )
      end
    end
    

    改动说明:

    • 用Rails.root.join替代字符串拼接,避免多环境路径编码问题
    • 以rb(二进制只读)模式读取文件,屏蔽平台相关的换行符自动转换
    • 预先加载文件内容到内存StringIO,ActiveStorage计算校验和、上传文件时都能读取完整内容,不会因文件指针偏移读到空内容。
  2. 排查Git二进制文件转换问题
    如果测试运行环境(如Docker容器)的xlsx文件是通过Git拉取的,检查Git的autocrlf配置,避免二进制xlsx文件被当成文本文件自动转换换行符,导致文件内容损坏。可在仓库根目录新增.gitattributes文件,指定xlsx文件为二进制类型:

    *.xlsx binary
    

    修改后重新拉取代码/重建测试环境,确保文件内容与本地一致。

  3. 校验验证(可选)
    如果需要确认问题根源,可在创建实例后打印原文件与挂载文件的校验和,确认是否一致:

    @loan_migration = create(:migration_session, :loan, cooperative: @cooperative, management: @manager)
    # 调试打印MD5校验和
    puts "原文件MD5: #{Digest::MD5.file(Rails.root.join('public/payment_migration.xlsx')).hexdigest}"
    puts "挂载文件MD5: #{Digest::MD5.hexdigest(@loan_migration.excel_file.blob.download)}"
    

    两个值不一致则确认是文件内容不匹配导致的校验失败,直接采用第一步的修改即可解决。


内容的提问来源于stack exchange,提问作者Dedy Puji

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.07 00:36:00