You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何测试Active Storage尺寸校验?遇OpenStruct未初始化错误

解决ActiveStorageValidations测试中的OpenStruct未初始化错误

问题场景

已安装active_storage_validations gem用于Active Storage的校验,相关代码如下:

Gemfile配置:

gem 'active_storage_validations'

Asset模型:

# Asset Model
class Asset < ApplicationRecord
  has_one_attached :portrait

  validates(
    :portrait,
    content_type: ['image/png', 'image/jpeg', 'image/svg+xml'],
    dimension: { width: { in: 8..512 }, height: { in: 8..512 } },
    size: { less_than: 250.kilobytes }
  )
end

RSpec测试代码:

# Asset test
require 'rails_helper'

RSpec.describe Asset do
  it { is_expected.to validate_dimensions_of(:portrait).width_between(8..512).height_between(8..512) }
end

运行测试时抛出以下错误,非测试环境无此问题:

Asset validations is expected to validate the image dimensions of :portrait
     Failure/Error: it { is_expected.to validate_dimensions_of(:portrait).width_between(8..512).height_between(8..512) }
     
     NameError:
       uninitialized constant ActiveStorageValidations::Matchers::OpenStruct

解决方案

该错误是因为RSpec测试环境未自动加载Ruby标准库OpenStruct,而active_storage_validations的校验匹配器内部依赖了它。只需在测试配置文件中手动引入即可:

  1. 打开spec/rails_helper.rb(或spec/spec_helper.rb)
  2. 在文件开头添加以下代码:
require 'ostruct'

重新运行测试即可解决该错误。

内容的提问来源于stack exchange,提问作者Chiara Ani

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 12:17:08