Skip to content

Commit 1adbd0b

Browse files
author
Derek Lindahl
committed
Add naive type casting for mock resources
1 parent c1cc0f7 commit 1adbd0b

File tree

2 files changed

+28
-5
lines changed

2 files changed

+28
-5
lines changed

lib/frenetic/resource_mockery.rb

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,11 +47,25 @@ def default_attributes
4747
def build_params(params)
4848
raw_params = (params || {}).with_indifferent_access
4949
defaults = default_attributes.with_indifferent_access
50-
@params = defaults.deep_merge(raw_params)
50+
@params = cast_types(defaults.deep_merge(raw_params))
5151
end
5252

5353
def build_structure
5454
@structure = OpenStruct.new(@attrs)
5555
end
56+
57+
# A naive attempt to cast the attribute types of the incoming mock data
58+
# based on any available type information provided in :default_attributes
59+
def cast_types(params)
60+
default_attributes.each do |key, value|
61+
params[key] = case true
62+
when value.is_a?(String) then String(params[key])
63+
when value.is_a?(Float) then Float(params[key])
64+
when value.is_a?(Integer) then Integer(params[key])
65+
else params[key]
66+
end
67+
end
68+
params
69+
end
5670
end
5771
end

spec/resource_mockery_spec.rb

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@
1111
Class.new(my_temp_resource) do
1212
def self.default_attributes
1313
{
14+
id: 1,
15+
price: 0.0,
1416
qux: 'qux',
1517
_embedded: {
1618
embedded_resource: {
@@ -24,7 +26,9 @@ def self.default_attributes
2426

2527
let(:params) do
2628
{
27-
foo: 1,
29+
id: '1',
30+
foo: 'bar',
31+
price: '0.0',
2832
bar: 'baz',
2933
_embedded: {
3034
embedded_resource: {
@@ -52,16 +56,21 @@ def self.default_attributes
5256
subject { super().properties }
5357

5458
it 'returns a hash of available properties' do
55-
expect(subject).to include 'foo' => 'fixnum'
59+
expect(subject).to include 'id' => 'fixnum'
60+
expect(subject).to include 'price' => 'float'
61+
expect(subject).to include 'foo' => 'string'
62+
expect(subject).to include 'foo' => 'string'
5663
expect(subject).to include 'bar' => 'string'
5764
end
5865
end
5966

6067
describe '#attributes' do
6168
subject { super().attributes }
6269

63-
it 'returns a hash of the resources attributes' do
64-
expect(subject).to include 'foo' => 1
70+
it 'returns a hash of the resources type-casted attributes' do
71+
expect(subject).to include 'id' => 1
72+
expect(subject).to include 'price' => 0.0
73+
expect(subject).to include 'foo' => 'bar'
6574
expect(subject).to include 'bar' => 'baz'
6675
expect(subject).to include 'qux' => 'qux'
6776
expect(subject['_embedded']['embedded_resource']).to include 'plugh' => 'xyzzy'

0 commit comments

Comments
 (0)