-
Notifications
You must be signed in to change notification settings - Fork 154
Expand file tree
/
Copy pathentity_spec.rb
More file actions
1101 lines (910 loc) · 38.2 KB
/
entity_spec.rb
File metadata and controls
1101 lines (910 loc) · 38.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
require 'spec_helper'
describe Grape::Entity do
let(:fresh_class) { Class.new(Grape::Entity) }
context 'class methods' do
subject { fresh_class }
describe '.expose' do
context 'multiple attributes' do
it 'is able to add multiple exposed attributes with a single call' do
subject.expose :name, :email, :location
subject.exposures.size.should == 3
end
it 'sets the same options for all exposures passed' do
subject.expose :name, :email, :location, documentation: true
subject.exposures.values.each { |v| v.should == { documentation: true } }
end
end
context 'option validation' do
it 'makes sure that :as only works on single attribute calls' do
expect { subject.expose :name, :email, as: :foo }.to raise_error ArgumentError
expect { subject.expose :name, as: :foo }.not_to raise_error
end
it 'makes sure that :format_with as a proc cannot be used with a block' do
expect { subject.expose :name, format_with: proc {} {} }.to raise_error ArgumentError
end
it 'makes sure unknown options are not silently ignored' do
expect { subject.expose :name, unknown: nil }.to raise_error ArgumentError
end
end
context 'with a block' do
it 'errors out if called with multiple attributes' do
expect { subject.expose(:name, :email) { true } }.to raise_error ArgumentError
end
it 'references an instance of the entity with :using option' do
module EntitySpec
class SomeObject1
attr_accessor :prop1
def initialize
@prop1 = "value1"
end
end
class BogusEntity < Grape::Entity
expose :prop1
end
end
subject.expose(:bogus, using: EntitySpec::BogusEntity) do |entity|
entity.prop1 = "MODIFIED 2"
entity
end
object = EntitySpec::SomeObject1.new
value = subject.represent(object).send(:value_for, :bogus)
value.should be_instance_of EntitySpec::BogusEntity
prop1 = value.send(:value_for, :prop1)
prop1.should == "MODIFIED 2"
end
context 'with parameters passed to the block' do
it 'sets the :proc option in the exposure options' do
block = lambda { |_| true }
subject.expose :name, using: 'Awesome', &block
subject.exposures[:name].should == { proc: block, using: 'Awesome' }
end
it 'references an instance of the entity without any options' do
subject.expose(:size) { |_| self }
subject.represent(Hash.new).send(:value_for, :size).should be_an_instance_of fresh_class
end
end
context 'with no parameters passed to the block' do
it 'adds a nested exposure' do
subject.expose :awesome do
subject.expose :nested do
subject.expose :moar_nested, as: 'weee'
end
subject.expose :another_nested, using: 'Awesome'
end
subject.exposures.should == {
awesome: {},
awesome__nested: { nested: true },
awesome__nested__moar_nested: { as: 'weee', nested: true },
awesome__another_nested: { using: 'Awesome', nested: true }
}
end
it 'represents the exposure as a hash of its nested exposures' do
subject.expose :awesome do
subject.expose(:nested) { |_| "value" }
subject.expose(:another_nested) { |_| "value" }
end
subject.represent({}).send(:value_for, :awesome).should == {
nested: "value",
another_nested: "value"
}
end
it 'does not represent attributes, declared inside nested exposure, outside of it' do
subject.expose :awesome do
subject.expose(:nested) { |_| "value" }
subject.expose(:another_nested) { |_| "value" }
subject.expose :second_level_nested do
subject.expose(:deeply_exposed_attr) { |_| "value" }
end
end
subject.represent({}).serializable_hash.should == {
awesome: {
nested: "value",
another_nested: "value",
second_level_nested: {
deeply_exposed_attr: "value"
}
}
}
end
it "complex nested attributes" do
class ClassRoom < Grape::Entity
expose(:parents, using: 'Parent') { |_| [{}, {}] }
end
class Person < Grape::Entity
expose :user do
expose(:in_first) { |_| 'value' }
end
end
class Student < Person
expose :user do
expose(:user_id) { |_| 'value' }
expose(:user_display_id, as: :display_id) { |_| 'value' }
end
end
class Parent < Person
expose(:children, using: 'Student') { |_| [{}, {}] }
end
ClassRoom.represent({}).serializable_hash.should == {
parents: [
{
user: { in_first: 'value' },
children: [
{ user: { in_first: 'value', user_id: "value", display_id: "value" } },
{ user: { in_first: 'value', user_id: "value", display_id: "value" } }
]
},
{
user: { in_first: 'value' },
children: [
{ user: { in_first: 'value', user_id: "value", display_id: "value" } },
{ user: { in_first: 'value', user_id: "value", display_id: "value" } }
]
}
]
}
end
it 'is safe if its nested exposures are safe' do
subject.with_options safe: true do
subject.expose :awesome do
subject.expose(:nested) { |_| "value" }
end
subject.expose :not_awesome do
subject.expose :nested
end
end
valid_keys = subject.represent({}).valid_exposures.keys
valid_keys.include?(:awesome).should == true && \
valid_keys.include?(:not_awesome).should == false
end
end
end
context 'inherited exposures' do
it 'returns exposures from an ancestor' do
subject.expose :name, :email
child_class = Class.new(subject)
child_class.exposures.should eq(subject.exposures)
end
it 'returns exposures from multiple ancestor' do
subject.expose :name, :email
parent_class = Class.new(subject)
child_class = Class.new(parent_class)
child_class.exposures.should eq(subject.exposures)
end
it 'returns descendant exposures as a priority' do
subject.expose :name, :email
child_class = Class.new(subject)
child_class.expose :name do |_|
'foo'
end
subject.exposures[:name].should_not have_key :proc
child_class.exposures[:name].should have_key :proc
end
end
context 'register formatters' do
let(:date_formatter) { lambda { |date| date.strftime('%m/%d/%Y') } }
it 'registers a formatter' do
subject.format_with :timestamp, &date_formatter
subject.formatters[:timestamp].should_not be_nil
end
it 'inherits formatters from ancestors' do
subject.format_with :timestamp, &date_formatter
child_class = Class.new(subject)
child_class.formatters.should == subject.formatters
end
it 'does not allow registering a formatter without a block' do
expect { subject.format_with :foo }.to raise_error ArgumentError
end
it 'formats an exposure with a registered formatter' do
subject.format_with :timestamp do |date|
date.strftime('%m/%d/%Y')
end
subject.expose :birthday, format_with: :timestamp
model = { birthday: Time.gm(2012, 2, 27) }
subject.new(double(model)).as_json[:birthday].should == '02/27/2012'
end
it 'formats an exposure with a :format_with lambda that returns a value from the entity instance' do
object = Hash.new
subject.expose(:size, format_with: lambda { |value| self.object.class.to_s })
subject.represent(object).send(:value_for, :size).should == object.class.to_s
end
it 'formats an exposure with a :format_with symbol that returns a value from the entity instance' do
subject.format_with :size_formatter do |date|
self.object.class.to_s
end
object = Hash.new
subject.expose(:size, format_with: :size_formatter)
subject.represent(object).send(:value_for, :size).should == object.class.to_s
end
end
end
describe '.with_options' do
it 'raises an error for unknown options' do
block = proc do
with_options(unknown: true) do
expose :awesome_thing
end
end
expect { subject.class_eval(&block) }.to raise_error ArgumentError
end
it 'applies the options to all exposures inside' do
subject.class_eval do
with_options(if: { awesome: true }) do
expose :awesome_thing, using: 'Awesome'
end
end
subject.exposures[:awesome_thing].should == { if: { awesome: true }, using: 'Awesome' }
end
it 'allows for nested .with_options' do
subject.class_eval do
with_options(if: { awesome: true }) do
with_options(using: 'Something') do
expose :awesome_thing
end
end
end
subject.exposures[:awesome_thing].should == { if: { awesome: true }, using: 'Something' }
end
it 'overrides nested :as option' do
subject.class_eval do
with_options(as: :sweet) do
expose :awesome_thing, as: :extra_smooth
end
end
subject.exposures[:awesome_thing].should == { as: :extra_smooth }
end
it "merges nested :if option" do
match_proc = lambda { |obj, opts| true }
subject.class_eval do
# Symbol
with_options(if: :awesome) do
# Hash
with_options(if: { awesome: true }) do
# Proc
with_options(if: match_proc) do
# Hash (override existing key and merge new key)
with_options(if: { awesome: false, less_awesome: true }) do
expose :awesome_thing
end
end
end
end
end
subject.exposures[:awesome_thing].should == {
if: { awesome: false, less_awesome: true },
if_extras: [:awesome, match_proc]
}
end
it 'merges nested :unless option' do
match_proc = lambda { |obj, opts| true }
subject.class_eval do
# Symbol
with_options(unless: :awesome) do
# Hash
with_options(unless: { awesome: true }) do
# Proc
with_options(unless: match_proc) do
# Hash (override existing key and merge new key)
with_options(unless: { awesome: false, less_awesome: true }) do
expose :awesome_thing
end
end
end
end
end
subject.exposures[:awesome_thing].should == {
unless: { awesome: false, less_awesome: true },
unless_extras: [:awesome, match_proc]
}
end
it 'overrides nested :using option' do
subject.class_eval do
with_options(using: 'Something') do
expose :awesome_thing, using: 'SomethingElse'
end
end
subject.exposures[:awesome_thing].should == { using: 'SomethingElse' }
end
it 'aliases :with option to :using option' do
subject.class_eval do
with_options(using: 'Something') do
expose :awesome_thing, with: 'SomethingElse'
end
end
subject.exposures[:awesome_thing].should == { using: 'SomethingElse' }
end
it 'overrides nested :proc option' do
match_proc = lambda { |obj, opts| 'more awesomer' }
subject.class_eval do
with_options(proc: lambda { |obj, opts| 'awesome' }) do
expose :awesome_thing, proc: match_proc
end
end
subject.exposures[:awesome_thing].should == { proc: match_proc }
end
it 'overrides nested :documentation option' do
subject.class_eval do
with_options(documentation: { desc: 'Description.' }) do
expose :awesome_thing, documentation: { desc: 'Other description.' }
end
end
subject.exposures[:awesome_thing].should == { documentation: { desc: 'Other description.' } }
end
end
describe '.represent' do
it 'returns a single entity if called with one object' do
subject.represent(Object.new).should be_kind_of(subject)
end
it 'returns a single entity if called with a hash' do
subject.represent(Hash.new).should be_kind_of(subject)
end
it 'returns multiple entities if called with a collection' do
representation = subject.represent(4.times.map { Object.new })
representation.should be_kind_of Array
representation.size.should == 4
representation.reject { |r| r.kind_of?(subject) }.should be_empty
end
it 'adds the collection: true option if called with a collection' do
representation = subject.represent(4.times.map { Object.new })
representation.each { |r| r.options[:collection].should be_true }
end
it 'returns a serialized hash of a single object if serializable: true' do
subject.expose(:awesome) { |_| true }
representation = subject.represent(Object.new, serializable: true)
representation.should == { awesome: true }
end
it 'returns a serialized array of hashes of multiple objects if serializable: true' do
subject.expose(:awesome) { |_| true }
representation = subject.represent(2.times.map { Object.new }, serializable: true)
representation.should == [{ awesome: true }, { awesome: true }]
end
end
describe '.root' do
context 'with singular and plural root keys' do
before(:each) do
subject.root 'things', 'thing'
end
context 'with a single object' do
it 'allows a root element name to be specified' do
representation = subject.represent(Object.new)
representation.should be_kind_of Hash
representation.should have_key 'thing'
representation['thing'].should be_kind_of(subject)
end
end
context 'with an array of objects' do
it 'allows a root element name to be specified' do
representation = subject.represent(4.times.map { Object.new })
representation.should be_kind_of Hash
representation.should have_key 'things'
representation['things'].should be_kind_of Array
representation['things'].size.should == 4
representation['things'].reject { |r| r.kind_of?(subject) }.should be_empty
end
end
context 'it can be overridden' do
it 'can be disabled' do
representation = subject.represent(4.times.map { Object.new }, root: false)
representation.should be_kind_of Array
representation.size.should == 4
representation.reject { |r| r.kind_of?(subject) }.should be_empty
end
it 'can use a different name' do
representation = subject.represent(4.times.map { Object.new }, root: 'others')
representation.should be_kind_of Hash
representation.should have_key 'others'
representation['others'].should be_kind_of Array
representation['others'].size.should == 4
representation['others'].reject { |r| r.kind_of?(subject) }.should be_empty
end
end
end
context 'with singular root key' do
before(:each) do
subject.root nil, 'thing'
end
context 'with a single object' do
it 'allows a root element name to be specified' do
representation = subject.represent(Object.new)
representation.should be_kind_of Hash
representation.should have_key 'thing'
representation['thing'].should be_kind_of(subject)
end
end
context 'with an array of objects' do
it 'allows a root element name to be specified' do
representation = subject.represent(4.times.map { Object.new })
representation.should be_kind_of Array
representation.size.should == 4
representation.reject { |r| r.kind_of?(subject) }.should be_empty
end
end
end
context 'with plural root key' do
before(:each) do
subject.root 'things'
end
context 'with a single object' do
it 'allows a root element name to be specified' do
subject.represent(Object.new).should be_kind_of(subject)
end
end
context 'with an array of objects' do
it 'allows a root element name to be specified' do
representation = subject.represent(4.times.map { Object.new })
representation.should be_kind_of Hash
representation.should have_key('things')
representation['things'].should be_kind_of Array
representation['things'].size.should == 4
representation['things'].reject { |r| r.kind_of?(subject) }.should be_empty
end
end
end
end
describe '#initialize' do
it 'takes an object and an optional options hash' do
expect { subject.new(Object.new) }.not_to raise_error
expect { subject.new }.to raise_error ArgumentError
expect { subject.new(Object.new, {}) }.not_to raise_error
end
it 'has attribute readers for the object and options' do
entity = subject.new('abc', {})
entity.object.should == 'abc'
entity.options.should == {}
end
end
end
context 'instance methods' do
let(:model) { double(attributes) }
let(:attributes) {
{
name: 'Bob Bobson',
email: 'bob@example.com',
birthday: Time.gm(2012, 2, 27),
fantasies: ['Unicorns', 'Double Rainbows', 'Nessy'],
friends: [
double(name: "Friend 1", email: 'friend1@example.com', fantasies: [], birthday: Time.gm(2012, 2, 27), friends: []),
double(name: "Friend 2", email: 'friend2@example.com', fantasies: [], birthday: Time.gm(2012, 2, 27), friends: [])
]
}
}
subject { fresh_class.new(model) }
describe '#serializable_hash' do
it 'does not throw an exception if a nil options object is passed' do
expect { fresh_class.new(model).serializable_hash(nil) }.not_to raise_error
end
it 'does not blow up when the model is nil' do
fresh_class.expose :name
expect { fresh_class.new(nil).serializable_hash }.not_to raise_error
end
context "with safe option" do
it 'does not throw an exception when an attribute is not found on the object' do
fresh_class.expose :name, :nonexistent_attribute, safe: true
expect { fresh_class.new(model).serializable_hash }.not_to raise_error
end
it "does not expose attributes that don't exist on the object" do
fresh_class.expose :email, :nonexistent_attribute, :name, safe: true
res = fresh_class.new(model).serializable_hash
res.should have_key :email
res.should_not have_key :nonexistent_attribute
res.should have_key :name
end
it "does not expose attributes that don't exist on the object, even with criteria" do
fresh_class.expose :email
fresh_class.expose :nonexistent_attribute, safe: true, if: lambda { false }
fresh_class.expose :nonexistent_attribute2, safe: true, if: lambda { true }
res = fresh_class.new(model).serializable_hash
res.should have_key :email
res.should_not have_key :nonexistent_attribute
res.should_not have_key :nonexistent_attribute2
end
end
context "without safe option" do
it 'throws an exception when an attribute is not found on the object' do
fresh_class.expose :name, :nonexistent_attribute
expect { fresh_class.new(model).serializable_hash }.to raise_error
end
it "exposes attributes that don't exist on the object only when they are generated by a block" do
fresh_class.expose :nonexistent_attribute do |model, _|
"well, I do exist after all"
end
res = fresh_class.new(model).serializable_hash
res.should have_key :nonexistent_attribute
end
it "does not expose attributes that are generated by a block but have not passed criteria" do
fresh_class.expose :nonexistent_attribute, proc: lambda { |model, _|
"I exist, but it is not yet my time to shine"
}, if: lambda { |model, _| false }
res = fresh_class.new(model).serializable_hash
res.should_not have_key :nonexistent_attribute
end
end
it "exposes attributes that don't exist on the object only when they are generated by a block with options" do
module EntitySpec
class TestEntity < Grape::Entity
end
end
fresh_class.expose :nonexistent_attribute, using: EntitySpec::TestEntity do |model, _|
"well, I do exist after all"
end
res = fresh_class.new(model).serializable_hash
res.should have_key :nonexistent_attribute
end
it "does not expose attributes that are generated by a block but have not passed criteria" do
fresh_class.expose :nonexistent_attribute, proc: lambda { |model, _|
"I exist, but it is not yet my time to shine"
}, if: lambda { |model, _| false }
res = fresh_class.new(model).serializable_hash
res.should_not have_key :nonexistent_attribute
end
context '#serializable_hash' do
module EntitySpec
class EmbeddedExample
def serializable_hash(opts = {})
{ abc: 'def' }
end
end
class EmbeddedExampleWithHash
def name
"abc"
end
def embedded
{ a: nil, b: EmbeddedExample.new }
end
end
class EmbeddedExampleWithMany
def name
"abc"
end
def embedded
[EmbeddedExample.new, EmbeddedExample.new]
end
end
class EmbeddedExampleWithOne
def name
"abc"
end
def embedded
EmbeddedExample.new
end
end
end
it 'serializes embedded objects which respond to #serializable_hash' do
fresh_class.expose :name, :embedded
presenter = fresh_class.new(EntitySpec::EmbeddedExampleWithOne.new)
presenter.serializable_hash.should == { name: "abc", embedded: { abc: "def" } }
end
it 'serializes embedded arrays of objects which respond to #serializable_hash' do
fresh_class.expose :name, :embedded
presenter = fresh_class.new(EntitySpec::EmbeddedExampleWithMany.new)
presenter.serializable_hash.should == { name: "abc", embedded: [{ abc: "def" }, { abc: "def" }] }
end
it 'serializes embedded hashes of objects which respond to #serializable_hash' do
fresh_class.expose :name, :embedded
presenter = fresh_class.new(EntitySpec::EmbeddedExampleWithHash.new)
presenter.serializable_hash.should == { name: "abc", embedded: { a: nil, b: { abc: "def" } } }
end
end
end
describe '#value_for' do
before do
fresh_class.class_eval do
expose :name, :email
expose :friends, using: self
expose :computed do |_, options|
options[:awesome]
end
expose :birthday, format_with: :timestamp
def timestamp(date)
date.strftime('%m/%d/%Y')
end
expose :fantasies, format_with: lambda { |f| f.reverse }
end
end
it 'passes through bare expose attributes' do
subject.send(:value_for, :name).should == attributes[:name]
end
it 'instantiates a representation if that is called for' do
rep = subject.send(:value_for, :friends)
rep.reject { |r| r.is_a?(fresh_class) }.should be_empty
rep.first.serializable_hash[:name].should == 'Friend 1'
rep.last.serializable_hash[:name].should == 'Friend 2'
end
context 'child representations' do
it 'disables root key name for child representations' do
module EntitySpec
class FriendEntity < Grape::Entity
root 'friends', 'friend'
expose :name, :email
end
end
fresh_class.class_eval do
expose :friends, using: EntitySpec::FriendEntity
end
rep = subject.send(:value_for, :friends)
rep.should be_kind_of Array
rep.reject { |r| r.is_a?(EntitySpec::FriendEntity) }.should be_empty
rep.first.serializable_hash[:name].should == 'Friend 1'
rep.last.serializable_hash[:name].should == 'Friend 2'
end
it "passes through the proc which returns an array of objects with custom options(:using)" do
module EntitySpec
class FriendEntity < Grape::Entity
root 'friends', 'friend'
expose :name, :email
end
end
fresh_class.class_eval do
expose :custom_friends, using: EntitySpec::FriendEntity do |user, options|
user.friends
end
end
rep = subject.send(:value_for, :custom_friends)
rep.should be_kind_of Array
rep.reject { |r| r.is_a?(EntitySpec::FriendEntity) }.should be_empty
rep.first.serializable_hash.should == { name: 'Friend 1', email: 'friend1@example.com' }
rep.last.serializable_hash.should == { name: 'Friend 2', email: 'friend2@example.com' }
end
it "passes through the proc which returns single object with custom options(:using)" do
module EntitySpec
class FriendEntity < Grape::Entity
root 'friends', 'friend'
expose :name, :email
end
end
fresh_class.class_eval do
expose :first_friend, using: EntitySpec::FriendEntity do |user, options|
user.friends.first
end
end
rep = subject.send(:value_for, :first_friend)
rep.should be_kind_of EntitySpec::FriendEntity
rep.serializable_hash.should == { name: 'Friend 1', email: 'friend1@example.com' }
end
it "passes through the proc which returns empty with custom options(:using)" do
module EntitySpec
class FriendEntity < Grape::Entity
root 'friends', 'friend'
expose :name, :email
end
end
fresh_class.class_eval do
expose :first_friend, using: EntitySpec::FriendEntity do |user, options|
end
end
rep = subject.send(:value_for, :first_friend)
rep.should be_kind_of EntitySpec::FriendEntity
rep.serializable_hash.should be_nil
end
it 'passes through custom options' do
module EntitySpec
class FriendEntity < Grape::Entity
root 'friends', 'friend'
expose :name
expose :email, if: { user_type: :admin }
end
end
fresh_class.class_eval do
expose :friends, using: EntitySpec::FriendEntity
end
rep = subject.send(:value_for, :friends)
rep.should be_kind_of Array
rep.reject { |r| r.is_a?(EntitySpec::FriendEntity) }.should be_empty
rep.first.serializable_hash[:email].should be_nil
rep.last.serializable_hash[:email].should be_nil
rep = subject.send(:value_for, :friends, user_type: :admin)
rep.should be_kind_of Array
rep.reject { |r| r.is_a?(EntitySpec::FriendEntity) }.should be_empty
rep.first.serializable_hash[:email].should == 'friend1@example.com'
rep.last.serializable_hash[:email].should == 'friend2@example.com'
end
it 'ignores the :collection parameter in the source options' do
module EntitySpec
class FriendEntity < Grape::Entity
root 'friends', 'friend'
expose :name
expose :email, if: { collection: true }
end
end
fresh_class.class_eval do
expose :friends, using: EntitySpec::FriendEntity
end
rep = subject.send(:value_for, :friends, collection: false)
rep.should be_kind_of Array
rep.reject { |r| r.is_a?(EntitySpec::FriendEntity) }.should be_empty
rep.first.serializable_hash[:email].should == 'friend1@example.com'
rep.last.serializable_hash[:email].should == 'friend2@example.com'
end
end
it 'calls through to the proc if there is one' do
subject.send(:value_for, :computed, awesome: 123).should == 123
end
it 'returns a formatted value if format_with is passed' do
subject.send(:value_for, :birthday).should == '02/27/2012'
end
it 'returns a formatted value if format_with is passed a lambda' do
subject.send(:value_for, :fantasies).should == ['Nessy', 'Double Rainbows', 'Unicorns']
end
it "tries instance methods on the entity first" do
module EntitySpec
class DelegatingEntity < Grape::Entity
root 'friends', 'friend'
expose :name
expose :email
private
def name
"cooler name"
end
end
end
friend = double("Friend", name: "joe", email: "joe@example.com")
rep = EntitySpec::DelegatingEntity.new(friend)
rep.send(:value_for, :name).should == "cooler name"
rep.send(:value_for, :email).should == "joe@example.com"
end
context "using" do
before do
module EntitySpec
class UserEntity < Grape::Entity
expose :name, :email
end
end
end
it "string" do
fresh_class.class_eval do
expose :friends, using: "EntitySpec::UserEntity"
end
rep = subject.send(:value_for, :friends)
rep.should be_kind_of Array
rep.size.should == 2
rep.all? { |r| r.is_a?(EntitySpec::UserEntity) }.should be_true
end
it 'class' do
fresh_class.class_eval do
expose :friends, using: EntitySpec::UserEntity
end
rep = subject.send(:value_for, :friends)
rep.should be_kind_of Array
rep.size.should == 2
rep.all? { |r| r.is_a?(EntitySpec::UserEntity) }.should be_true
end
end
context "object from DSL class" do
it "should use the DSL class's entity" do
module EntitySpec
class ObjectWithDSL
include Grape::Entity::DSL
entity do
expose(:foo) { "FOO" }
end
def as_json
{ bar: "BAR" }
end
alias_method :serializable_hash, :as_json
end
end
fresh_class.expose(:object_with_dsl)
model.should_receive(:object_with_dsl).and_return(EntitySpec::ObjectWithDSL.new)
subject.send(:value_for, :object_with_dsl).should be_kind_of(EntitySpec::ObjectWithDSL::Entity)
end
end
end
describe '#documentation' do
it 'returns an empty hash is no documentation is provided' do
fresh_class.expose :name
subject.documentation.should == {}
end
it 'returns each defined documentation hash' do
doc = { type: "foo", desc: "bar" }
fresh_class.expose :name, documentation: doc
fresh_class.expose :email, documentation: doc
fresh_class.expose :birthday
subject.documentation.should == { name: doc, email: doc }
end
it 'returns each defined documentation hash with :as param considering' do
doc = { type: "foo", desc: "bar" }
fresh_class.expose :name, documentation: doc, as: :label
fresh_class.expose :email, documentation: doc
fresh_class.expose :birthday
subject.documentation.should == { label: doc, email: doc }
end
end
describe '#key_for' do
it 'returns the attribute if no :as is set' do
fresh_class.expose :name
subject.class.send(:key_for, :name).should == :name
end
it 'returns a symbolized version of the attribute' do
fresh_class.expose :name
subject.class.send(:key_for, 'name').should == :name
end
it 'returns the :as alias if one exists' do
fresh_class.expose :name, as: :nombre
subject.class.send(:key_for, 'name').should == :nombre
end
end
describe '#conditions_met?' do
it 'only passes through hash :if exposure if all attributes match' do
exposure_options = { if: { condition1: true, condition2: true } }
subject.send(:conditions_met?, exposure_options, {}).should be_false
subject.send(:conditions_met?, exposure_options, condition1: true).should be_false
subject.send(:conditions_met?, exposure_options, condition1: true, condition2: true).should be_true