Skip to content

Commit

Permalink
Fixed parameter validation to pass inherited types.
Browse files Browse the repository at this point in the history
  • Loading branch information
xevix authored and dblock committed Mar 7, 2014
1 parent 190bb5d commit 4934baa
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 1 deletion.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ Next Release

#### Fixes

* [#590](https://github.com/intridea/grape/pull/590): Fix Issue Where Endpoint Param of Type Integer Cannot Set Values Array - [@xevix](https://github.com/xevix)
* [#586](https://github.com/intridea/grape/pull/586): Do not repeat the same validation error messages - [@kiela](https://github.com/kiela)
* [#508](https://github.com/intridea/grape/pull/508): Allow parameters, such as content encoding, in `content_type` - [@dm1try](https://github.com/dm1try).
* [#492](https://github.com/intridea/grape/pull/492): Don't allow to have nil value when a param is required and has a list of allowed values - [@Antti](https://github.com/Antti).
Expand Down
2 changes: 1 addition & 1 deletion lib/grape/validations.rb
Original file line number Diff line number Diff line change
Expand Up @@ -240,7 +240,7 @@ def validates(attrs, validations)
end

# type should be compatible with values array, if both exist
if coerce_type && values && values.any? { |v| !v.instance_of?(coerce_type) }
if coerce_type && values && values.any? { |v| !v.kind_of?(coerce_type) }
raise Grape::Exceptions::IncompatibleOptionValues.new(:type, coerce_type, :values, values)
end

Expand Down
20 changes: 20 additions & 0 deletions spec/grape/validations/values_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,13 @@ class API < Grape::API
get '/lambda' do
{ type: params[:type] }
end

params do
requires :type, type: Integer, desc: "An integer", values: [10, 11], default: 10
end
get '/values/coercion' do
{ type: params[:type] }
end
end
end
end
Expand Down Expand Up @@ -115,4 +122,17 @@ def app
subject.params { optional :type, values: ['valid-type1', 'valid-type2', 'valid-type3'], type: Symbol }
}.to raise_error Grape::Exceptions::IncompatibleOptionValues
end

it 'allows values to be a kind of the coerced type not just an instance of it' do
get("/values/coercion", type: 10)
last_response.status.should eq 200
last_response.body.should eq({ type: 10 }.to_json)
end

it 'raises IncompatibleOptionValues when values contains a value that is not a kind of the type' do
subject = Class.new(Grape::API)
expect {
subject.params { requires :type, values: [10.5, 11], type: Integer }
}.to raise_error Grape::Exceptions::IncompatibleOptionValues
end
end

0 comments on commit 4934baa

Please sign in to comment.