Skip to content

Commit

Permalink
Fix JSON::ParserError when image data is an invalid json string (#37)
Browse files Browse the repository at this point in the history
* Fix JSON::ParserError when image data is an invalid json string

* Fix the test description for invalid json strings

* Uniformize test descriptions for empty strings

* Use more complete example of invalid JSON strings in tests

* Rescue JSON::ParserError strictly around parse_values methods

* Return earlier from the validate_each methods
  • Loading branch information
gael-ian committed Apr 4, 2020
1 parent 74d9a59 commit 7572767
Show file tree
Hide file tree
Showing 4 changed files with 25 additions and 3 deletions.
Expand Up @@ -10,7 +10,13 @@ def self.helper_method_name
end

def validate_each(record, attribute, value)
values = parse_values(value)
begin
values = parse_values(value)
rescue JSON::ParserError
record.errors.add attribute, :invalid
return
end

return if values.empty?

mode = option_value(record, :mode)
Expand Down
8 changes: 7 additions & 1 deletion lib/file_validators/validators/file_size_validator.rb
Expand Up @@ -14,7 +14,13 @@ def self.helper_method_name
end

def validate_each(record, attribute, value)
values = parse_values(value)
begin
values = parse_values(value)
rescue JSON::ParserError
record.errors.add attribute, :invalid
return
end

return if values.empty?

options.slice(*CHECKS.keys).each do |option, option_value|
Expand Down
Expand Up @@ -364,6 +364,11 @@ class Person
before { subject.avatar = '' }
it { is_expected.to be_valid }
end

context 'invalid json string' do
before { subject.avatar = '{filename":"img140910_88338.jpg","content_type":"image/jpeg","size":13150}' }
it { is_expected.not_to be_valid }
end
end

context 'image data as hash' do
Expand Down
7 changes: 6 additions & 1 deletion spec/integration/file_size_validator_integration_spec.rb
Expand Up @@ -240,10 +240,15 @@ class Person
it { is_expected.to be_valid }
end

context 'empty json string' do
context 'empty string' do
before { subject.avatar = '' }
it { is_expected.to be_valid }
end

context 'invalid json string' do
before { subject.avatar = '{filename":"img140910_88338.GIF","content_type":"image/gif","size":33150}' }
it { is_expected.not_to be_valid }
end
end

context 'image data as hash' do
Expand Down

0 comments on commit 7572767

Please sign in to comment.