Skip to content

Commit

Permalink
fix bug for default value as proc when there is given options values
Browse files Browse the repository at this point in the history
  • Loading branch information
ShPakvel committed Oct 8, 2014
1 parent 834d06a commit d2e7949
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 1 deletion.
4 changes: 3 additions & 1 deletion lib/grape/validations/params_scope.rb
Original file line number Diff line number Diff line change
Expand Up @@ -104,10 +104,12 @@ def validates(attrs, validations)
default = validations[:default]
doc_attrs[:default] = default if default

default = default.call if default.is_a?(Proc)

values = validations[:values]
doc_attrs[:values] = values if values

values = (values.is_a?(Proc) ? values.call : values)
values = values.call if values.is_a?(Proc)

# default value should be present in values array, if both exist
if default && values && !values.include?(default)
Expand Down
38 changes: 38 additions & 0 deletions spec/grape/validations/validators/values_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,20 @@ class API < Grape::API
{ type: params[:type] }
end

params do
optional :type, values: ValuesModel.values, default: -> { ValuesModel.values.sample }
end
get '/default_lambda' do
{ type: params[:type] }
end

params do
optional :type, values: -> { ValuesModel.values }, default: -> { ValuesModel.values.sample }
end
get '/default_and_values_lambda' do
{ type: params[:type] }
end

params do
requires :type, type: Integer, desc: "An integer", values: [10, 11], default: 10
end
Expand Down Expand Up @@ -123,6 +137,30 @@ def app
expect(last_response.body).to eq({ error: "type does not have a valid value" }.to_json)
end

it 'validates default value from proc' do
get("/default_lambda")
expect(last_response.status).to eq 200
end

it 'validates default value from proc against values in a proc' do
get("/default_and_values_lambda")
expect(last_response.status).to eq 200
end

it 'raises IncompatibleOptionValues on an invalid default value from proc' do
subject = Class.new(Grape::API)
expect {
subject.params { optional :type, values: ['valid-type1', 'valid-type2', 'valid-type3'], default: -> { ValuesModel.values.sample + "_invalid" } }
}.to raise_error Grape::Exceptions::IncompatibleOptionValues
end

it 'raises IncompatibleOptionValues on an invalid default value from proc validating against values in a proc' do
subject = Class.new(Grape::API)
expect {
subject.params { optional :type, values: -> { ValuesModel.values }, default: -> { ValuesModel.values.sample + "_invalid" } }
}.to raise_error Grape::Exceptions::IncompatibleOptionValues
end

it 'raises IncompatibleOptionValues on an invalid default value' do
subject = Class.new(Grape::API)
expect {
Expand Down

0 comments on commit d2e7949

Please sign in to comment.