Skip to content

Commit 6d2e332

Browse files
authored
Merge pull request #1974 from ruby-grape/chore/primitive-coercer-spec
more tests for Grape::Validations::Types::PrimitiveCoercer
2 parents 341160c + 020a166 commit 6d2e332

File tree

2 files changed

+66
-2
lines changed

2 files changed

+66
-2
lines changed

lib/grape/validations/types/primitive_coercer.rb

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff 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
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
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

0 commit comments

Comments
 (0)