diff --git a/CHANGELOG.md b/CHANGELOG.md index bdda7ab3be..6ab7a42b35 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ * [#2370](https://github.com/ruby-grape/grape/pull/2370): Remove route_xyz method_missing deprecation - [@ericproulx](https://github.com/ericproulx). * [#2372](https://github.com/ruby-grape/grape/pull/2372): Fix `declared` method for hash params with overlapping names - [@jcagarcia](https://github.com/jcagarcia). * [#2373](https://github.com/ruby-grape/grape/pull/2373): Fix markdown files for following 1-line format - [@jcagarcia](https://github.com/jcagarcia). +* [#2382](https://github.com/ruby-grape/grape/pull/2382): Fix values validator for params wrapped in `with` block - [@numbata](https://github.com/numbata). * Your contribution here. ### 2.0.0 (2023/11/11) diff --git a/lib/grape/validations/validators/values_validator.rb b/lib/grape/validations/validators/values_validator.rb index 3be7d609b6..8475ffb822 100644 --- a/lib/grape/validations/validators/values_validator.rb +++ b/lib/grape/validations/validators/values_validator.rb @@ -85,7 +85,12 @@ def except_message end def required_for_root_scope? - @required && @scope.root? + return false unless @required + + scope = @scope + scope = scope.parent while scope.lateral? + + scope.root? end def validation_exception(attr_name, message) diff --git a/spec/grape/validations/validators/values_spec.rb b/spec/grape/validations/validators/values_spec.rb index d8ef17c95b..5d8daab914 100644 --- a/spec/grape/validations/validators/values_spec.rb +++ b/spec/grape/validations/validators/values_spec.rb @@ -261,6 +261,13 @@ def even?(value) optional :name, type: String, values: %w[a b], allow_blank: true end get '/allow_blank' + + params do + with(type: String) do + requires :type, values: ValuesModel.values + end + end + get 'values_wrapped_by_with_block' end end @@ -730,4 +737,13 @@ def app end end end + + context 'when wrapped by with block' do + it 'rejects an invalid value' do + get 'values_wrapped_by_with_block' + + expect(last_response.status).to eq 400 + expect(last_response.body).to eq({ error: 'type is missing, type does not have a valid value' }.to_json) + end + end end