diff --git a/CHANGELOG.md b/CHANGELOG.md index 44924a61e5..e4df3db3fc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ #### Fixes +* [#1977](https://github.com/ruby-grape/grape/pull/1977): Skip validation for a file if it is optional and nil - [@dnesteryuk](https://github.com/dnesteryuk). * [#1976](https://github.com/ruby-grape/grape/pull/1976): Ensure classes/modules listed for autoload really exist - [@dnesteryuk](https://github.com/dnesteryuk). * [#1971](https://github.com/ruby-grape/grape/pull/1971): Fix BigDecimal coercion - [@FlickStuart](https://github.com/FlickStuart). * [#1968](https://github.com/ruby-grape/grape/pull/1968): Fix args forwarding in Grape::Middleware::Stack#merge_with for ruby 2.7.0 - [@dm1try](https://github.com/dm1try). diff --git a/lib/grape/validations/types/file.rb b/lib/grape/validations/types/file.rb index 2802ace483..6b79389de4 100644 --- a/lib/grape/validations/types/file.rb +++ b/lib/grape/validations/types/file.rb @@ -8,6 +8,7 @@ module Types # this class is here only to assert that rack's handling has succeeded. class File def call(input) + return if input.nil? return InvalidValue.new unless coerced?(input) # Processing of multipart file objects diff --git a/spec/grape/validations_spec.rb b/spec/grape/validations_spec.rb index 3e8df50ff3..b1625d570e 100644 --- a/spec/grape/validations_spec.rb +++ b/spec/grape/validations_spec.rb @@ -11,14 +11,17 @@ def app describe 'params' do context 'optional' do - it 'validates when params is present' do + before do subject.params do optional :a_number, regexp: /^[0-9]+$/ + optional :attachment, type: File end subject.get '/optional' do 'optional works!' end + end + it 'validates when params is present' do get '/optional', a_number: 'string' expect(last_response.status).to eq(400) expect(last_response.body).to eq('a_number is invalid') @@ -29,14 +32,7 @@ def app end it "doesn't validate when param not present" do - subject.params do - optional :a_number, regexp: /^[0-9]+$/ - end - subject.get '/optional' do - 'optional works!' - end - - get '/optional' + get '/optional', a_number: nil, attachment: nil expect(last_response.status).to eq(200) expect(last_response.body).to eq('optional works!') end