File tree Expand file tree Collapse file tree 2 files changed +66
-2
lines changed
lib/grape/validations/types
spec/grape/validations/types Expand file tree Collapse file tree 2 files changed +66
-2
lines changed Original file line number Diff line number Diff line change @@ -6,12 +6,13 @@ module Grape
66 module Validations
77 module Types
88 # Coerces the given value to a type defined via a +type+ argument during
9- # initialization.
9+ # initialization. When +strict+ is true, it doesn't coerce a value but check
10+ # that it has the proper type.
1011 class PrimitiveCoercer < DryTypeCoercer
1112 MAPPING = {
1213 Grape ::API ::Boolean => DryTypes ::Params ::Bool ,
1314
14- # unfortunatelly , a +Params+ scope doesn't contain String
15+ # unfortunately , a +Params+ scope doesn't contain String
1516 String => DryTypes ::Coercible ::String ,
1617 BigDecimal => DryTypes ::Coercible ::Decimal
1718 } . freeze
Original file line number Diff line number Diff line change 1+ # frozen_string_literal: true
2+
3+ require 'spec_helper'
4+
5+ describe Grape ::Validations ::Types ::PrimitiveCoercer do
6+ let ( :strict ) { false }
7+
8+ subject { described_class . new ( type , strict ) }
9+
10+ describe '.call' do
11+ context 'Boolean' do
12+ let ( :type ) { Grape ::API ::Boolean }
13+
14+ it 'coerces to Boolean' do
15+ expect ( subject . call ( 0 ) ) . to eq ( false )
16+ end
17+ end
18+
19+ context 'String' do
20+ let ( :type ) { String }
21+
22+ it 'coerces to String' do
23+ expect ( subject . call ( 10 ) ) . to eq ( '10' )
24+ end
25+ end
26+
27+ context 'BigDecimal' do
28+ let ( :type ) { BigDecimal }
29+
30+ it 'coerces to BigDecimal' do
31+ expect ( subject . call ( 5 ) ) . to eq ( BigDecimal ( 5 ) )
32+ end
33+ end
34+
35+ context 'the strict mode' do
36+ let ( :strict ) { true }
37+
38+ context 'Boolean' do
39+ let ( :type ) { Grape ::API ::Boolean }
40+
41+ it 'returns an error when the given value is not Boolean' do
42+ expect ( subject . call ( 1 ) ) . to be_instance_of ( Grape ::Validations ::Types ::InvalidValue )
43+ end
44+
45+ it 'returns a value as it is when the given value is Boolean' do
46+ expect ( subject . call ( true ) ) . to eq ( true )
47+ end
48+ end
49+
50+ context 'BigDecimal' do
51+ let ( :type ) { BigDecimal }
52+
53+ it 'returns an error when the given value is not BigDecimal' do
54+ expect ( subject . call ( 1 ) ) . to be_instance_of ( Grape ::Validations ::Types ::InvalidValue )
55+ end
56+
57+ it 'returns a value as it is when the given value is BigDecimal' do
58+ expect ( subject . call ( BigDecimal ( 0 ) ) ) . to eq ( BigDecimal ( 0 ) )
59+ end
60+ end
61+ end
62+ end
63+ end
You can’t perform that action at this time.
0 commit comments