diff --git a/lib/grape/validations/validators/length_validator.rb b/lib/grape/validations/validators/length_validator.rb index bcd0c95592..78ea580988 100644 --- a/lib/grape/validations/validators/length_validator.rb +++ b/lib/grape/validations/validators/length_validator.rb @@ -18,6 +18,8 @@ def initialize(attrs, options, required, scope, **opts) def validate_param!(attr_name, params) param = params[attr_name] + return if param.nil? + raise ArgumentError, "parameter #{param} does not support #length" unless param.respond_to?(:length) return unless (!@min.nil? && param.length < @min) || (!@max.nil? && param.length > @max) diff --git a/spec/grape/validations/validators/length_spec.rb b/spec/grape/validations/validators/length_spec.rb index 8fa9f84876..e9c08376d9 100644 --- a/spec/grape/validations/validators/length_spec.rb +++ b/spec/grape/validations/validators/length_spec.rb @@ -81,6 +81,12 @@ post 'zero_max' do end + params do + optional :list, type: [Integer], length: { min: 2 } + end + post '/no_param' do + end + params do requires :list, type: [Integer], length: { min: 2, message: 'not match' } end @@ -187,6 +193,16 @@ end end + describe '/no_param' do + context 'no raises errors' do + it do + expect do + post '/no_param', list: nil + end.not_to raise_error + end + end + end + describe '/type_is_not_array' do context 'raises an error' do it do