Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Don't allow to have nil value when required & have allowed values. #492

Merged
merged 1 commit into from
Oct 24, 2013
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@ Next Release

* Your contribution here.

#### Fixes

* [#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)

0.6.1
=====

Expand Down
3 changes: 2 additions & 1 deletion lib/grape/validations/values.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,12 @@ module Validations
class ValuesValidator < Validator
def initialize(attrs, options, required, scope)
@values = options
@required = required
super
end

def validate_param!(attr_name, params)
if params[attr_name] && !@values.include?(params[attr_name])
if (params[attr_name] || @required) && !@values.include?(params[attr_name])
raise Grape::Exceptions::Validation, param: @scope.full_name(attr_name), message_key: :values
end
end
Expand Down
6 changes: 6 additions & 0 deletions spec/grape/validations/values_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,12 @@ def app
last_response.body.should eq({ error: "type does not have a valid value" }.to_json)
end

it 'does not allow nil value for a parameter' do
get("/", type: nil)
last_response.status.should eq 400
last_response.body.should eq({ error: "type does not have a valid value" }.to_json)
end

it 'allows a valid default value' do
get("/default/valid")
last_response.status.should eq 200
Expand Down