Skip to content

Commit 72a11e9

Browse files
committed
Fix bug with coercion
1 parent 4f97cfc commit 72a11e9

File tree

3 files changed

+11
-7
lines changed

3 files changed

+11
-7
lines changed

lib/grape/validations/types/build_coercer.rb

+9-1
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,15 @@ def self.build_coercer(type, method = nil)
2626
converter_options = {
2727
nullify_blank: true
2828
}
29-
conversion_type = type
29+
conversion_type = if method == JSON
30+
# becase we want just parsed JSON content:
31+
# if type is Array and data is `"{}"`
32+
# result will be [] because Virtus converts Hashes
33+
# to arrays
34+
Object
35+
else
36+
type
37+
end
3038

3139
# Use a special coercer for multiply-typed parameters.
3240
if Types.multiple?(type)

spec/grape/validations/validators/coerce_spec.rb

+2-3
Original file line numberDiff line numberDiff line change
@@ -382,7 +382,7 @@ class User
382382
expect(JSON.parse(last_response.body)).to eq([0, 0, 0, 0])
383383
end
384384

385-
it 'uses parse where available', focus: true do
385+
it 'uses parse where available' do
386386
subject.params do
387387
requires :ints, type: Array, coerce_with: JSON do
388388
requires :i, type: Integer
@@ -398,10 +398,9 @@ class User
398398
expect(last_response.status).to eq(400)
399399
expect(last_response.body).to eq('ints is invalid')
400400

401-
# TODO: there is a bug in coercer. '{"i":1,"j":"2"}' transformed into [["i", 1], ["j", "2"]] WTF?
402401
get '/ints', ints: '{"i":1,"j":"2"}'
403402
expect(last_response.status).to eq(400)
404-
expect(last_response.body).to eq('ints[0][i] is missing, ints[0][i] is invalid, ints[0][j] is missing')
403+
expect(last_response.body).to eq('ints is invalid')
405404

406405
get '/ints', ints: '[{"i":"1","j":"2"}]'
407406
expect(last_response.status).to eq(200)

spec/spec_helper.rb

-3
Original file line numberDiff line numberDiff line change
@@ -25,8 +25,5 @@
2525
config.include Rack::Test::Methods
2626
config.raise_errors_for_deprecations!
2727

28-
config.filter_run :focus
29-
config.run_all_when_everything_filtered = true
30-
3128
config.before(:each) { Grape::Util::InheritableSetting.reset_global! }
3229
end

0 commit comments

Comments
 (0)