如何测试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的校验匹配器内部依赖了它。只需在测试配置文件中手动引入即可:
- 打开
spec/rails_helper.rb(或spec/spec_helper.rb) - 在文件开头添加以下代码:
require 'ostruct'
重新运行测试即可解决该错误。
内容的提问来源于stack exchange,提问作者Chiara Ani
相关产品推荐
相关产品推荐

