File: entity_spec.rb

package info (click to toggle)
ruby-grape-entity 1.0.1-2
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 456 kB
  • sloc: ruby: 3,335; makefile: 6
file content (2179 lines) | stat: -rw-r--r-- 81,153 bytes parent folder | download
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
# frozen_string_literal: true

require 'spec_helper'
require 'ostruct'

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
          expect(subject.root_exposures.size).to eq 3
        end

        it 'sets the same options for all.root_exposures passed' do
          subject.expose :name, :email, :location, documentation: true
          subject.root_exposures.each { |v| expect(v.documentation).to eq 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
          # rubocop:disable Style/BlockDelimiters
          expect {
            subject.expose :name, format_with: proc {} do
              p 'hi'
            end
          }.to raise_error ArgumentError
          # rubocop:enable Style/BlockDelimiters
        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 :merge option' do
        let(:nested_hash) do
          { something: { like_nested_hash: true }, special: { like_nested_hash: '12' } }
        end

        it 'merges an exposure to the root' do
          subject.expose(:something, merge: true)
          expect(subject.represent(nested_hash).serializable_hash).to eq(nested_hash[:something])
        end

        it 'allows to solve collisions providing a lambda to a :merge option' do
          subject.expose(:something, merge: true)
          subject.expose(:special, merge: ->(_, v1, v2) { v1 && v2 ? 'brand new val' : v2 })
          expect(subject.represent(nested_hash).serializable_hash).to eq(like_nested_hash: 'brand new val')
        end

        context 'and nested object is nil' do
          let(:nested_hash) do
            { something: nil, special: { like_nested_hash: '12' } }
          end

          it 'adds nothing to output' do
            subject.expose(:something, merge: true)
            subject.expose(:special)
            expect(subject.represent(nested_hash).serializable_hash).to eq(special: { like_nested_hash: '12' })
          end
        end
      end

      context 'with :expose_nil option' do
        let(:a) { nil }
        let(:b) { nil }
        let(:c) { 'value' }

        context 'when model is a PORO' do
          let(:model) { Model.new(a, b, c) }

          before do
            stub_const 'Model', Class.new
            Model.class_eval do
              attr_accessor :a, :b, :c

              def initialize(a, b, c)
                @a = a
                @b = b
                @c = c
              end
            end
          end

          context 'when expose_nil option is not provided' do
            it 'exposes nil attributes' do
              subject.expose(:a)
              subject.expose(:b)
              subject.expose(:c)
              expect(subject.represent(model).serializable_hash).to eq(a: nil, b: nil, c: 'value')
            end
          end

          context 'when expose_nil option is true' do
            it 'exposes nil attributes' do
              subject.expose(:a, expose_nil: true)
              subject.expose(:b, expose_nil: true)
              subject.expose(:c)
              expect(subject.represent(model).serializable_hash).to eq(a: nil, b: nil, c: 'value')
            end
          end

          context 'when expose_nil option is false' do
            it 'does not expose nil attributes' do
              subject.expose(:a, expose_nil: false)
              subject.expose(:b, expose_nil: false)
              subject.expose(:c)
              expect(subject.represent(model).serializable_hash).to eq(c: 'value')
            end

            it 'is only applied per attribute' do
              subject.expose(:a, expose_nil: false)
              subject.expose(:b)
              subject.expose(:c)
              expect(subject.represent(model).serializable_hash).to eq(b: nil, c: 'value')
            end

            it 'raises an error when applied to multiple attribute exposures' do
              expect { subject.expose(:a, :b, :c, expose_nil: false) }.to raise_error ArgumentError
            end
          end

          context 'when expose_nil option is false and block passed' do
            it 'does not expose if block returns nil' do
              subject.expose(:a, expose_nil: false) do |_obj, options|
                options[:option_a]
              end
              subject.expose(:b)
              subject.expose(:c)
              expect(subject.represent(model).serializable_hash).to eq(b: nil, c: 'value')
            end

            it 'exposes is block returns a value' do
              subject.expose(:a, expose_nil: false) do |_obj, options|
                options[:option_a]
              end
              subject.expose(:b)
              subject.expose(:c)
              expect(subject.represent(model, option_a: 100).serializable_hash).to eq(a: 100, b: nil, c: 'value')
            end
          end
        end

        context 'when model is a hash' do
          let(:model) { { a: a, b: b, c: c } }

          context 'when expose_nil option is not provided' do
            it 'exposes nil attributes' do
              subject.expose(:a)
              subject.expose(:b)
              subject.expose(:c)
              expect(subject.represent(model).serializable_hash).to eq(a: nil, b: nil, c: 'value')
            end
          end

          context 'when expose_nil option is true' do
            it 'exposes nil attributes' do
              subject.expose(:a, expose_nil: true)
              subject.expose(:b, expose_nil: true)
              subject.expose(:c)
              expect(subject.represent(model).serializable_hash).to eq(a: nil, b: nil, c: 'value')
            end
          end

          context 'when expose_nil option is false' do
            it 'does not expose nil attributes' do
              subject.expose(:a, expose_nil: false)
              subject.expose(:b, expose_nil: false)
              subject.expose(:c)
              expect(subject.represent(model).serializable_hash).to eq(c: 'value')
            end

            it 'is only applied per attribute' do
              subject.expose(:a, expose_nil: false)
              subject.expose(:b)
              subject.expose(:c)
              expect(subject.represent(model).serializable_hash).to eq(b: nil, c: 'value')
            end

            it 'raises an error when applied to multiple attribute exposures' do
              expect { subject.expose(:a, :b, :c, expose_nil: false) }.to raise_error ArgumentError
            end
          end
        end

        context 'with nested structures' do
          let(:model) { { a: a, b: b, c: { d: nil, e: nil, f: { g: nil, h: nil } } } }

          context 'when expose_nil option is false' do
            it 'does not expose nil attributes' do
              subject.expose(:a, expose_nil: false)
              subject.expose(:b)
              subject.expose(:c) do
                subject.expose(:d, expose_nil: false)
                subject.expose(:e)
                subject.expose(:f) do
                  subject.expose(:g, expose_nil: false)
                  subject.expose(:h)
                end
              end

              expect(subject.represent(model).serializable_hash).to eq(b: nil, c: { e: nil, f: { h: nil } })
            end
          end
        end
      end

      context 'with :default option' do
        let(:a) { nil }
        let(:b) { nil }
        let(:c) { 'value' }

        context 'when model is a PORO' do
          let(:model) { Model.new(a, b, c) }

          before do
            stub_const 'Model', Class.new
            Model.class_eval do
              attr_accessor :a, :b, :c

              def initialize(a, b, c)
                @a = a
                @b = b
                @c = c
              end
            end
          end

          context 'when default option is not provided' do
            it 'exposes attributes values' do
              subject.expose(:a)
              subject.expose(:b)
              subject.expose(:c)
              expect(subject.represent(model).serializable_hash).to eq(a: nil, b: nil, c: 'value')
            end
          end

          context 'when default option is set' do
            it 'exposes default values for attributes' do
              subject.expose(:a, default: 'a')
              subject.expose(:b, default: false)
              subject.expose(:c, default: 'c')
              expect(subject.represent(model).serializable_hash).to eq(a: 'a', b: false, c: 'value')
            end
          end

          context 'when default option is set and block passed' do
            it 'return default value if block returns nil' do
              subject.expose(:a, default: 'a') do |_obj, _options|
                nil
              end
              subject.expose(:b)
              subject.expose(:c)
              expect(subject.represent(model).serializable_hash).to eq(a: 'a', b: nil, c: 'value')
            end

            it 'return value from block if block returns a value' do
              subject.expose(:a, default: 'a') do |_obj, _options|
                100
              end
              subject.expose(:b)
              subject.expose(:c)
              expect(subject.represent(model).serializable_hash).to eq(a: 100, b: nil, c: 'value')
            end
          end
        end

        context 'when model is a hash' do
          let(:model) { { a: a, b: b, c: c } }

          context 'when expose_nil option is not provided' do
            it 'exposes nil attributes' do
              subject.expose(:a)
              subject.expose(:b)
              subject.expose(:c)
              expect(subject.represent(model).serializable_hash).to eq(a: nil, b: nil, c: 'value')
            end
          end

          context 'when expose_nil option is true' do
            it 'exposes nil attributes' do
              subject.expose(:a, expose_nil: true)
              subject.expose(:b, expose_nil: true)
              subject.expose(:c)
              expect(subject.represent(model).serializable_hash).to eq(a: nil, b: nil, c: 'value')
            end
          end

          context 'when expose_nil option is false' do
            it 'does not expose nil attributes' do
              subject.expose(:a, expose_nil: false)
              subject.expose(:b, expose_nil: false)
              subject.expose(:c)
              expect(subject.represent(model).serializable_hash).to eq(c: 'value')
            end

            it 'is only applied per attribute' do
              subject.expose(:a, expose_nil: false)
              subject.expose(:b)
              subject.expose(:c)
              expect(subject.represent(model).serializable_hash).to eq(b: nil, c: 'value')
            end

            it 'raises an error when applied to multiple attribute exposures' do
              expect { subject.expose(:a, :b, :c, expose_nil: false) }.to raise_error ArgumentError
            end
          end
        end

        context 'with nested structures' do
          let(:model) { { a: a, b: b, c: { d: nil, e: nil, f: { g: nil, h: nil } } } }

          context 'when expose_nil option is false' do
            it 'does not expose nil attributes' do
              subject.expose(:a, expose_nil: false)
              subject.expose(:b)
              subject.expose(:c) do
                subject.expose(:d, expose_nil: false)
                subject.expose(:e)
                subject.expose(:f) do
                  subject.expose(:g, expose_nil: false)
                  subject.expose(:h)
                end
              end

              expect(subject.represent(model).serializable_hash).to eq(b: nil, c: { e: nil, f: { h: nil } })
            end
          end
        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).value_for(:bogus)
          expect(value).to be_instance_of EntitySpec::BogusEntity

          prop1 = value.value_for(:prop1)
          expect(prop1).to eq 'MODIFIED 2'
        end

        context 'with parameters passed to the block' do
          it 'sets the :proc option in the exposure options' do
            block = ->(_) { true }
            subject.expose :name, using: 'Awesome', &block
            exposure = subject.find_exposure(:name)
            expect(exposure.subexposure.block).to eq(block)
            expect(exposure.using_class_name).to eq('Awesome')
          end

          it 'references an instance of the entity without any options' do
            subject.expose(:size) { |_| self }
            expect(subject.represent({}).value_for(:size)).to be_an_instance_of fresh_class
          end
        end

        describe 'blocks' do
          class SomeObject
            def method_without_args
              'result'
            end

            def raises_argument_error
              raise ArgumentError, 'something different'
            end
          end

          describe 'with block passed in' do
            specify do
              subject.expose :that_method_without_args do |object|
                object.method_without_args
              end

              object = SomeObject.new

              value = subject.represent(object).value_for(:that_method_without_args)
              expect(value).to eq('result')
            end

            it 'does not suppress ArgumentError' do
              subject.expose :raises_argument_error do |object|
                object.raises_argument_error
              end

              object = SomeObject.new
              expect do
                subject.represent(object).value_for(:raises_argument_error)
              end.to raise_error(ArgumentError, 'something different')
            end
          end

          context 'with block passed in via &' do
            if RUBY_VERSION.start_with?('3')
              specify do
                subject.expose :that_method_without_args, &:method_without_args
                subject.expose :method_without_args, as: :that_method_without_args_again

                object = SomeObject.new
                expect do
                  subject.represent(object).value_for(:that_method_without_args)
                end.to raise_error Grape::Entity::Deprecated

                value2 = subject.represent(object).value_for(:that_method_without_args_again)
                expect(value2).to eq('result')
              end
            else
              specify do
                subject.expose :that_method_without_args_again, &:method_without_args

                object = SomeObject.new

                value2 = subject.represent(object).value_for(:that_method_without_args_again)
                expect(value2).to eq('result')
              end
            end
          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

            awesome = subject.find_exposure(:awesome)
            nested = awesome.find_nested_exposure(:nested)
            another_nested = awesome.find_nested_exposure(:another_nested)
            moar_nested = nested.find_nested_exposure(:moar_nested)

            expect(awesome).to be_nesting
            expect(nested).to_not be_nil
            expect(another_nested).to_not be_nil
            expect(another_nested.using_class_name).to eq('Awesome')
            expect(moar_nested).to_not be_nil
            expect(moar_nested.key(subject)).to eq(:weee)
          end

          it 'represents the exposure as a hash of its nested.root_exposures' do
            subject.expose :awesome do
              subject.expose(:nested) { |_| 'value' }
              subject.expose(:another_nested) { |_| 'value' }
            end

            expect(subject.represent({}).value_for(:awesome)).to eq(
              nested: 'value',
              another_nested: 'value'
            )
          end

          it 'does not represent nested.root_exposures whose conditions are not met' do
            subject.expose :awesome do
              subject.expose(:condition_met, if: ->(_, _) { true }) { |_| 'value' }
              subject.expose(:condition_not_met, if: ->(_, _) { false }) { |_| 'value' }
            end

            expect(subject.represent({}).value_for(:awesome)).to eq(condition_met: '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

            expect(subject.represent({}).serializable_hash).to eq(
              awesome: {
                nested: 'value',
                another_nested: 'value',
                second_level_nested: {
                  deeply_exposed_attr: 'value'
                }
              }
            )
          end

          it 'merges 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

            expect(ClassRoom.represent({}).serializable_hash).to eq(
              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 'merges results of deeply nested double.root_exposures inside of nesting exposure' do
            entity = Class.new(Grape::Entity) do
              expose :data do
                expose :something do
                  expose(:x) { |_| 'x' }
                end
                expose :something do
                  expose(:y) { |_| 'y' }
                end
              end
            end
            expect(entity.represent({}).serializable_hash).to eq(
              data: {
                something: {
                  x: 'x',
                  y: 'y'
                }
              }
            )
          end

          it 'serializes deeply nested presenter exposures' do
            e = Class.new(Grape::Entity) do
              expose :f
            end
            subject.expose :a do
              subject.expose :b do
                subject.expose :c do
                  subject.expose :lol, using: e
                end
              end
            end
            expect(subject.represent(lol: { f: 123 }).serializable_hash).to eq(
              a: { b: { c: { lol: { f: 123 } } } }
            )
          end

          it 'is safe if its nested.root_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
            expect(subject.represent({}, serializable: true)).to eq(
              awesome: {
                nested: 'value'
              },
              not_awesome: {
                nested: nil
              }
            )
          end
          it 'merges attriutes if :merge option is passed' do
            user_entity = Class.new(Grape::Entity)
            admin_entity = Class.new(Grape::Entity)
            user_entity.expose(:id, :name)
            admin_entity.expose(:id, :name)

            subject.expose(:profiles) do
              subject.expose(:users, merge: true, using: user_entity)
              subject.expose(:admins, merge: true, using: admin_entity)
            end

            subject.expose :awesome do
              subject.expose(:nested, merge: true) { |_| { just_a_key: 'value' } }
              subject.expose(:another_nested, merge: true) { |_| { just_another_key: 'value' } }
            end

            additional_hash = { users: [{ id: 1, name: 'John' }, { id: 2, name: 'Jay' }],
                                admins: [{ id: 3, name: 'Jack' }, { id: 4, name: 'James' }] }
            expect(subject.represent(additional_hash).serializable_hash).to eq(
              profiles: additional_hash[:users] + additional_hash[:admins],
              awesome: { just_a_key: 'value', just_another_key: 'value' }
            )
          end
        end
      end

      context 'inherited.root_exposures' do
        it 'returns.root_exposures from an ancestor' do
          subject.expose :name, :email
          child_class = Class.new(subject)

          expect(child_class.root_exposures).to eq(subject.root_exposures)
        end

        it 'returns.root_exposures from multiple ancestor' do
          subject.expose :name, :email
          parent_class = Class.new(subject)
          child_class  = Class.new(parent_class)

          expect(child_class.root_exposures).to eq(subject.root_exposures)
        end

        it 'returns descendant.root_exposures as a priority' do
          subject.expose :name, :email
          child_class = Class.new(subject)
          child_class.expose :name do |_|
            'foo'
          end

          expect(subject.represent({ name: 'bar' }, serializable: true)).to eq(email: nil, name: 'bar')
          expect(child_class.represent({ name: 'bar' }, serializable: true)).to eq(email: nil, name: 'foo')
        end

        it 'not overrides exposure by default' do
          subject.expose :name
          child_class = Class.new(subject)
          child_class.expose :name, as: :child_name

          expect(subject.represent({ name: 'bar' }, serializable: true)).to eq(name: 'bar')
          expect(child_class.represent({ name: 'bar' }, serializable: true)).to eq(name: 'bar', child_name: 'bar')
        end

        it 'overrides parent class exposure when option is specified' do
          subject.expose :name
          child_class = Class.new(subject)
          child_class.expose :name, as: :child_name, override: true

          expect(subject.represent({ name: 'bar' }, serializable: true)).to eq(name: 'bar')
          expect(child_class.represent({ name: 'bar' }, serializable: true)).to eq(child_name: 'bar')
        end
      end

      context 'register formatters' do
        let(:date_formatter) { ->(date) { date.strftime('%m/%d/%Y') } }

        it 'registers a formatter' do
          subject.format_with :timestamp, &date_formatter

          expect(subject.formatters[:timestamp]).not_to be_nil
        end

        it 'inherits formatters from ancestors' do
          subject.format_with :timestamp, &date_formatter
          child_class = Class.new(subject)

          expect(child_class.formatters).to eq 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) }
          expect(subject.new(double(model)).as_json[:birthday]).to eq '02/27/2012'
        end

        it 'formats an exposure with a :format_with lambda that returns a value from the entity instance' do
          object = {}

          subject.expose(:size, format_with: ->(_value) { object.class.to_s })
          expect(subject.represent(object).value_for(:size)).to eq 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|
            object.class.to_s
          end

          object = {}

          subject.expose(:size, format_with: :size_formatter)
          expect(subject.represent(object).value_for(:size)).to eq object.class.to_s
        end

        it 'works global on Grape::Entity' do
          Grape::Entity.format_with :size_formatter do |_date|
            object.class.to_s
          end
          object = {}

          subject.expose(:size, format_with: :size_formatter)
          expect(subject.represent(object).value_for(:size)).to eq object.class.to_s
        end
      end

      it 'works global on Grape::Entity' do
        Grape::Entity.expose :a
        object = { a: 11, b: 22 }
        expect(Grape::Entity.represent(object).value_for(:a)).to eq 11
        subject.expose :b
        expect(subject.represent(object).value_for(:a)).to eq 11
        expect(subject.represent(object).value_for(:b)).to eq 22
        Grape::Entity.unexpose :a
      end
    end

    describe '.unexpose' do
      it 'is able to remove exposed attributes' do
        subject.expose :name, :email
        subject.unexpose :email

        expect(subject.root_exposures.length).to eq 1
        expect(subject.root_exposures[0].attribute).to eq :name
      end

      context 'inherited.root_exposures' do
        it 'when called from child class, only removes from the attribute from child' do
          subject.expose :name, :email
          child_class = Class.new(subject)
          child_class.unexpose :email

          expect(child_class.root_exposures.length).to eq 1
          expect(child_class.root_exposures[0].attribute).to eq :name
          expect(subject.root_exposures[0].attribute).to eq :name
          expect(subject.root_exposures[1].attribute).to eq :email
        end

        context 'when called from the parent class' do
          it 'remove from parent and do not remove from child classes' do
            subject.expose :name, :email
            child_class = Class.new(subject)
            subject.unexpose :email

            expect(subject.root_exposures.length).to eq 1
            expect(subject.root_exposures[0].attribute).to eq :name
            expect(child_class.root_exposures[0].attribute).to eq :name
            expect(child_class.root_exposures[1].attribute).to eq :email
          end
        end
      end

      it 'does not allow unexposing inside of nesting exposures' do
        expect do
          Class.new(Grape::Entity) do
            expose :something do
              expose :x
              unexpose :x
            end
          end
        end.to raise_error(/You cannot call 'unexpose`/)
      end

      it 'works global on Grape::Entity' do
        Grape::Entity.expose :x
        expect(Grape::Entity.root_exposures[0].attribute).to eq(:x)
        Grape::Entity.unexpose :x
        expect(Grape::Entity.root_exposures).to eq([])
      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.root_exposures inside' do
        subject.class_eval do
          with_options(if: { awesome: true }) do
            expose :awesome_thing, using: 'Awesome'
          end
        end

        exposure = subject.find_exposure(:awesome_thing)
        expect(exposure.using_class_name).to eq('Awesome')
        expect(exposure.conditions[0].cond_hash).to eq(awesome: true)
      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

        exposure = subject.find_exposure(:awesome_thing)
        expect(exposure.using_class_name).to eq('Something')
        expect(exposure.conditions[0].cond_hash).to eq(awesome: true)
      end

      it 'overrides nested :as option' do
        subject.class_eval do
          with_options(as: :sweet) do
            expose :awesome_thing, as: :extra_smooth
          end
        end

        exposure = subject.find_exposure(:awesome_thing)
        expect(exposure.key(subject)).to eq :extra_smooth
      end

      it 'merges nested :if option' do
        match_proc = ->(_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

        exposure = subject.find_exposure(:awesome_thing)
        expect(exposure.conditions.any?(&:inversed?)).to be_falsey
        expect(exposure.conditions[0].symbol).to eq(:awesome)
        expect(exposure.conditions[1].block).to eq(match_proc)
        expect(exposure.conditions[2].cond_hash).to eq(awesome: false, less_awesome: true)
      end

      it 'merges nested :unless option' do
        match_proc = ->(_, _) { 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

        exposure = subject.find_exposure(:awesome_thing)
        expect(exposure.conditions.all?(&:inversed?)).to be_truthy
        expect(exposure.conditions[0].symbol).to eq(:awesome)
        expect(exposure.conditions[1].block).to eq(match_proc)
        expect(exposure.conditions[2].cond_hash).to eq(awesome: false, less_awesome: true)
      end

      it 'overrides nested :using option' do
        subject.class_eval do
          with_options(using: 'Something') do
            expose :awesome_thing, using: 'SomethingElse'
          end
        end

        exposure = subject.find_exposure(:awesome_thing)
        expect(exposure.using_class_name).to eq('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

        exposure = subject.find_exposure(:awesome_thing)
        expect(exposure.using_class_name).to eq('SomethingElse')
      end

      it 'overrides nested :proc option' do
        match_proc = ->(_obj, _opts) { 'more awesomer' }

        subject.class_eval do
          with_options(proc: ->(_obj, _opts) { 'awesome' }) do
            expose :awesome_thing, proc: match_proc
          end
        end

        exposure = subject.find_exposure(:awesome_thing)
        expect(exposure.block).to eq(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

        exposure = subject.find_exposure(:awesome_thing)
        expect(exposure.documentation).to eq(desc: 'Other description.')
      end

      it 'propagates expose_nil option' do
        subject.class_eval do
          with_options(expose_nil: false) do
            expose :awesome_thing
          end
        end

        exposure = subject.find_exposure(:awesome_thing)
        expect(exposure.conditions[0].inversed?).to be true
        expect(exposure.conditions[0].block.call(awesome_thing: nil)).to be true
      end

      it 'overrides nested :expose_nil option' do
        subject.class_eval do
          with_options(expose_nil: true) do
            expose :awesome_thing, expose_nil: false
            expose :other_awesome_thing
          end
        end

        exposure = subject.find_exposure(:awesome_thing)
        expect(exposure.conditions[0].inversed?).to be true
        expect(exposure.conditions[0].block.call(awesome_thing: nil)).to be true
        # Conditions are only added for exposures that do not expose nil
        exposure = subject.find_exposure(:other_awesome_thing)
        expect(exposure.conditions[0]).to be_nil
      end
    end

    describe '.represent' do
      it 'returns a single entity if called with one object' do
        expect(subject.represent(Object.new)).to be_kind_of(subject)
      end

      it 'returns a single entity if called with a hash' do
        expect(subject.represent({})).to be_kind_of(subject)
      end

      it 'returns multiple entities if called with a collection' do
        representation = subject.represent(Array.new(4) { Object.new })
        expect(representation).to be_kind_of Array
        expect(representation.size).to eq(4)
        expect(representation.reject { |r| r.is_a?(subject) }).to be_empty
      end

      it 'adds the collection: true option if called with a collection' do
        representation = subject.represent(Array.new(4) { Object.new })
        representation.each { |r| expect(r.options[:collection]).to 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)
        expect(representation).to eq(awesome: true)
      end

      it 'returns a serialized array of hashes of multiple objects if serializable: true' do
        subject.expose(:awesome) { |_| true }
        representation = subject.represent(Array.new(2) { Object.new }, serializable: true)
        expect(representation).to eq([{ awesome: true }, { awesome: true }])
      end

      it 'returns a serialized hash of a hash' do
        subject.expose(:awesome)
        representation = subject.represent({ awesome: true }, serializable: true)
        expect(representation).to eq(awesome: true)
      end

      it 'returns a serialized hash of an OpenStruct' do
        subject.expose(:awesome)
        representation = subject.represent(OpenStruct.new, serializable: true)
        expect(representation).to eq(awesome: nil)
      end

      it 'raises error if field not found' do
        subject.expose(:awesome)
        expect do
          subject.represent(Object.new, serializable: true)
        end.to raise_error(NoMethodError, /missing attribute `awesome'/)
      end

      context 'with specified fields' do
        it 'returns only specified fields with only option' do
          subject.expose(:id, :name, :phone)
          representation = subject.represent(OpenStruct.new, only: %i[id name], serializable: true)
          expect(representation).to eq(id: nil, name: nil)
        end

        it 'returns all fields except the ones specified in the except option' do
          subject.expose(:id, :name, :phone)
          representation = subject.represent(OpenStruct.new, except: [:phone], serializable: true)
          expect(representation).to eq(id: nil, name: nil)
        end

        it 'returns only fields specified in the only option and not specified in the except option' do
          subject.expose(:id, :name, :phone)
          representation = subject.represent(OpenStruct.new,
                                             only: %i[name phone],
                                             except: [:phone], serializable: true)
          expect(representation).to eq(name: nil)
        end

        context 'with strings or symbols passed to only and except' do
          let(:object) { OpenStruct.new(user: {}) }

          before do
            user_entity = Class.new(Grape::Entity)
            user_entity.expose(:id, :name, :email)

            subject.expose(:id, :name, :phone, :address)
            subject.expose(:user, using: user_entity)
          end

          it 'can specify "only" option attributes as strings' do
            representation = subject.represent(object, only: ['id', 'name', { 'user' => ['email'] }], serializable: true)
            expect(representation).to eq(id: nil, name: nil, user: { email: nil })
          end

          it 'can specify "except" option attributes as strings' do
            representation = subject.represent(object, except: ['id', 'name', { 'user' => ['email'] }], serializable: true)
            expect(representation).to eq(phone: nil, address: nil, user: { id: nil, name: nil })
          end

          it 'can specify "only" option attributes as symbols' do
            representation = subject.represent(object, only: [:name, :phone, { user: [:name] }], serializable: true)
            expect(representation).to eq(name: nil, phone: nil, user: { name: nil })
          end

          it 'can specify "except" option attributes as symbols' do
            representation = subject.represent(object, except: [:name, :phone, { user: [:name] }], serializable: true)
            expect(representation).to eq(id: nil, address: nil, user: { id: nil, email: nil })
          end

          it 'can specify "only" attributes as strings and symbols' do
            representation = subject.represent(object, only: [:id, 'address', { user: [:id, 'name'] }], serializable: true)
            expect(representation).to eq(id: nil, address: nil, user: { id: nil, name: nil })
          end

          it 'can specify "except" attributes as strings and symbols' do
            representation = subject.represent(object, except: [:id, 'address', { user: [:id, 'name'] }], serializable: true)
            expect(representation).to eq(name: nil, phone: nil, user: { email: nil })
          end

          context 'with nested attributes' do
            before do
              subject.expose :additional do
                subject.expose :something
              end
            end

            it 'preserves nesting' do
              expect(subject.represent({ something: 123 }, only: [{ additional: [:something] }], serializable: true)).to eq(
                additional: {
                  something: 123
                }
              )
            end
          end
        end

        it 'can specify children attributes with only' do
          user_entity = Class.new(Grape::Entity)
          user_entity.expose(:id, :name, :email)

          subject.expose(:id, :name, :phone)
          subject.expose(:user, using: user_entity)

          representation = subject.represent(OpenStruct.new(user: {}), only: [:id, :name, { user: %i[name email] }], serializable: true)
          expect(representation).to eq(id: nil, name: nil, user: { name: nil, email: nil })
        end

        it 'can specify children attributes with except' do
          user_entity = Class.new(Grape::Entity)
          user_entity.expose(:id, :name, :email)

          subject.expose(:id, :name, :phone)
          subject.expose(:user, using: user_entity)

          representation = subject.represent(OpenStruct.new(user: {}), except: [:phone, { user: [:id] }], serializable: true)
          expect(representation).to eq(id: nil, name: nil, user: { name: nil, email: nil })
        end

        it 'can specify children attributes with mixed only and except' do
          user_entity = Class.new(Grape::Entity)
          user_entity.expose(:id, :name, :email, :address)

          subject.expose(:id, :name, :phone, :mobile_phone)
          subject.expose(:user, using: user_entity)

          representation = subject.represent(OpenStruct.new(user: {}),
                                             only: [:id, :name, :phone, { user: %i[id name email] }],
                                             except: [:phone, { user: [:id] }], serializable: true)
          expect(representation).to eq(id: nil, name: nil, user: { name: nil, email: nil })
        end

        context 'specify attribute with exposure condition' do
          it 'returns only specified fields' do
            subject.expose(:id)
            subject.with_options(if: { condition: true }) do
              subject.expose(:name)
            end

            representation = subject.represent(OpenStruct.new, condition: true, only: %i[id name], serializable: true)
            expect(representation).to eq(id: nil, name: nil)
          end

          it 'does not return fields specified in the except option' do
            subject.expose(:id, :phone)
            subject.with_options(if: { condition: true }) do
              subject.expose(:name, :mobile_phone)
            end

            representation = subject.represent(OpenStruct.new, condition: true, except: %i[phone mobile_phone], serializable: true)
            expect(representation).to eq(id: nil, name: nil)
          end

          it 'choses proper exposure according to condition' do
            strategy1 = ->(_obj, _opts) { 'foo' }
            strategy2 = ->(_obj, _opts) { 'bar' }

            subject.expose :id, proc: strategy1
            subject.expose :id, proc: strategy2
            expect(subject.represent({}, condition: false, serializable: true)).to eq(id: 'bar')
            expect(subject.represent({}, condition: true, serializable: true)).to eq(id: 'bar')

            subject.unexpose_all

            subject.expose :id, proc: strategy1, if: :condition
            subject.expose :id, proc: strategy2
            expect(subject.represent({}, condition: false, serializable: true)).to eq(id: 'bar')
            expect(subject.represent({}, condition: true, serializable: true)).to eq(id: 'bar')

            subject.unexpose_all

            subject.expose :id, proc: strategy1
            subject.expose :id, proc: strategy2, if: :condition
            expect(subject.represent({}, condition: false, serializable: true)).to eq(id: 'foo')
            expect(subject.represent({}, condition: true, serializable: true)).to eq(id: 'bar')

            subject.unexpose_all

            subject.expose :id, proc: strategy1, if: :condition1
            subject.expose :id, proc: strategy2, if: :condition2
            expect(subject.represent({}, condition1: false, condition2: false, serializable: true)).to eq({})
            expect(subject.represent({}, condition1: false, condition2: true, serializable: true)).to eq(id: 'bar')
            expect(subject.represent({}, condition1: true, condition2: false, serializable: true)).to eq(id: 'foo')
            expect(subject.represent({}, condition1: true, condition2: true, serializable: true)).to eq(id: 'bar')
          end

          it 'does not merge nested exposures with plain hashes' do
            subject.expose(:id)
            subject.expose(:info, if: :condition1) do
              subject.expose :a, :b
              subject.expose(:additional, if: :condition2) do |_obj, _opts|
                {
                  x: 11, y: 22, c: 123
                }
              end
            end
            subject.expose(:info, if: :condition2) do
              subject.expose(:additional) do
                subject.expose :c
              end
            end
            subject.expose(:d, as: :info, if: :condition3)

            obj = { id: 123, a: 1, b: 2, c: 3, d: 4 }

            expect(subject.represent(obj, serializable: true)).to eq(id: 123)
            expect(subject.represent(obj, condition1: true, serializable: true)).to eq(id: 123, info: { a: 1, b: 2 })
            expect(subject.represent(obj, condition2: true, serializable: true)).to eq(
              id: 123,
              info: {
                additional: {
                  c: 3
                }
              }
            )
            expect(subject.represent(obj, condition1: true, condition2: true, serializable: true)).to eq(
              id: 123,
              info: {
                a: 1, b: 2, additional: { c: 3 }
              }
            )
            expect(subject.represent(obj, condition3: true, serializable: true)).to eq(id: 123, info: 4)
            expect(subject.represent(obj, condition1: true, condition2: true, condition3: true, serializable: true)).to eq(id: 123, info: 4)
          end
        end

        context 'attribute with alias' do
          it 'returns only specified fields' do
            subject.expose(:id)
            subject.expose(:name, as: :title)

            representation = subject.represent(OpenStruct.new, condition: true, only: %i[id title], serializable: true)
            expect(representation).to eq(id: nil, title: nil)
          end

          it 'does not return fields specified in the except option' do
            subject.expose(:id)
            subject.expose(:name, as: :title)
            subject.expose(:phone, as: :phone_number)

            representation = subject.represent(OpenStruct.new, condition: true, except: [:phone_number], serializable: true)
            expect(representation).to eq(id: nil, title: nil)
          end
        end

        context 'attribute that is an entity itself' do
          it 'returns correctly the children entity attributes' do
            user_entity = Class.new(Grape::Entity)
            user_entity.expose(:id, :name, :email)

            nephew_entity = Class.new(Grape::Entity)
            nephew_entity.expose(:id, :name, :email)

            subject.expose(:id, :name, :phone)
            subject.expose(:user, using: user_entity)
            subject.expose(:nephew, using: nephew_entity)

            representation = subject.represent(OpenStruct.new(user: {}),
                                               only: %i[id name user], except: [:nephew], serializable: true)
            expect(representation).to eq(id: nil, name: nil, user: { id: nil, name: nil, email: nil })
          end
        end

        context 'when NameError happens in a parameterized block_exposure' do
          before do
            subject.expose :raise_no_method_error do |_|
              foo
            end
          end

          it 'does not cause infinite loop' do
            expect { subject.represent({}, serializable: true) }.to raise_error(NameError)
          end
        end
      end
    end

    describe '.present_collection' do
      it 'make the objects accessible' do
        subject.present_collection true
        subject.expose :items

        representation = subject.represent(Array.new(4) { Object.new })
        expect(representation).to be_kind_of(subject)
        expect(representation.object).to be_kind_of(Hash)
        expect(representation.object).to have_key :items
        expect(representation.object[:items]).to be_kind_of Array
        expect(representation.object[:items].size).to be 4
      end

      it 'serializes items with my root name' do
        subject.present_collection true, :my_items
        subject.expose :my_items

        representation = subject.represent(Array.new(4) { Object.new }, serializable: true)
        expect(representation).to be_kind_of(Grape::Entity::Exposure::NestingExposure::OutputBuilder)
        expect(representation).to be_kind_of(Hash)
        expect(representation).to have_key :my_items
        expect(representation[:my_items]).to be_kind_of Array
        expect(representation[:my_items].size).to be 4
      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)
            expect(representation).to be_kind_of Hash
            expect(representation).to have_key 'thing'
            expect(representation['thing']).to 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(Array.new(4) { Object.new })
            expect(representation).to be_kind_of Hash
            expect(representation).to have_key 'things'
            expect(representation['things']).to be_kind_of Array
            expect(representation['things'].size).to eq 4
            expect(representation['things'].reject { |r| r.is_a?(subject) }).to be_empty
          end
        end

        context 'it can be overridden' do
          it 'can be disabled' do
            representation = subject.represent(Array.new(4) { Object.new }, root: false)
            expect(representation).to be_kind_of Array
            expect(representation.size).to eq 4
            expect(representation.reject { |r| r.is_a?(subject) }).to be_empty
          end
          it 'can use a different name' do
            representation = subject.represent(Array.new(4) { Object.new }, root: 'others')
            expect(representation).to be_kind_of Hash
            expect(representation).to have_key 'others'
            expect(representation['others']).to be_kind_of Array
            expect(representation['others'].size).to eq 4
            expect(representation['others'].reject { |r| r.is_a?(subject) }).to 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)
            expect(representation).to be_kind_of Hash
            expect(representation).to have_key 'thing'
            expect(representation['thing']).to 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(Array.new(4) { Object.new })
            expect(representation).to be_kind_of Array
            expect(representation.size).to eq 4
            expect(representation.reject { |r| r.is_a?(subject) }).to 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
            expect(subject.represent(Object.new)).to 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(Array.new(4) { Object.new })
            expect(representation).to be_kind_of Hash
            expect(representation).to have_key('things')
            expect(representation['things']).to be_kind_of Array
            expect(representation['things'].size).to eq 4
            expect(representation['things'].reject { |r| r.is_a?(subject) }).to be_empty
          end
        end
      end

      context 'inheriting from parent entity' do
        before(:each) do
          subject.root 'things', 'thing'
        end

        it 'inherits single root' do
          child_class = Class.new(subject)
          representation = child_class.represent(Object.new)
          expect(representation).to be_kind_of Hash
          expect(representation).to have_key 'thing'
          expect(representation['thing']).to be_kind_of(child_class)
        end

        it 'inherits array root root' do
          child_class = Class.new(subject)
          representation = child_class.represent(Array.new(4) { Object.new })
          expect(representation).to be_kind_of Hash
          expect(representation).to have_key('things')
          expect(representation['things']).to be_kind_of Array
          expect(representation['things'].size).to eq 4
          expect(representation['things'].reject { |r| r.is_a?(child_class) }).to be_empty
        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', {})
        expect(entity.object).to eq 'abc'
        expect(entity.options).to eq({})
      end
    end
  end

  context 'instance methods' do
    let(:model) { double(attributes) }

    let(:attributes) do
      {
        name: 'Bob Bobson',
        email: 'bob@example.com',
        birthday: Time.gm(2012, 2, 27),
        fantasies: ['Unicorns', 'Double Rainbows', 'Nessy'],
        characteristics: [
          { key: 'hair_color', value: 'brown' }
        ],
        friends: [
          double(name: 'Friend 1', email: 'friend1@example.com', characteristics: [], fantasies: [], birthday: Time.gm(2012, 2, 27), friends: []),
          double(name: 'Friend 2', email: 'friend2@example.com', characteristics: [], fantasies: [], birthday: Time.gm(2012, 2, 27), friends: [])
        ],
        extra: { key: 'foo', value: 'bar' },
        nested: [
          { name: 'n1', data: { key: 'ex1', value: 'v1' } },
          { name: 'n2', data: { key: 'ex2', value: 'v2' } }
        ]
      }
    end

    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 'exposes values of private method calls' do
          some_class = Class.new do
            define_method :name do
              true
            end
            private :name
          end
          fresh_class.expose :name, safe: true
          expect(fresh_class.new(some_class.new).serializable_hash).to eq(name: true)
        end

        it "does 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
          expect(res).to have_key :email
          expect(res).to have_key :nonexistent_attribute
          expect(res).to have_key :name
        end

        it "does expose attributes that don't exist on the object as nil" do
          fresh_class.expose :email, :nonexistent_attribute, :name, safe: true

          res = fresh_class.new(model).serializable_hash
          expect(res[:nonexistent_attribute]).to eq(nil)
        end

        it 'does expose attributes marked as safe if model is a hash object' do
          fresh_class.expose :name, safe: true

          res = fresh_class.new(name: 'myname').serializable_hash
          expect(res).to have_key :name
        end

        it "does expose attributes that don't exist on the object as nil if criteria is true" do
          fresh_class.expose :email
          fresh_class.expose :nonexistent_attribute, safe: true, if: ->(_obj, _opts) { false }
          fresh_class.expose :nonexistent_attribute2, safe: true, if: ->(_obj, _opts) { true }

          res = fresh_class.new(model).serializable_hash
          expect(res).to have_key :email
          expect(res).not_to have_key :nonexistent_attribute
          expect(res).to 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 NoMethodError
        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, _opts|
            'well, I do exist after all'
          end
          res = fresh_class.new(model).serializable_hash
          expect(res).to 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: ->(_model, _opts) { 'I exist, but it is not yet my time to shine' },
                             if: ->(_model, _opts) { false }
          res = fresh_class.new(model).serializable_hash
          expect(res).not_to 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, _opts|
          'well, I do exist after all'
        end
        res = fresh_class.new(model).serializable_hash
        expect(res).to have_key :nonexistent_attribute
      end

      it 'exposes attributes defined through module inclusion' do
        module SharedAttributes
          def a_value
            3.14
          end
        end
        fresh_class.include(SharedAttributes)
        fresh_class.expose :a_value
        res = fresh_class.new(model).serializable_hash
        expect(res[:a_value]).to eq(3.14)
      end

      it 'does not expose attributes that are generated by a block but have not passed criteria' do
        fresh_class.expose :nonexistent_attribute,
                           proc: ->(_, _) { 'I exist, but it is not yet my time to shine' },
                           if: ->(_, _) { false }
        res = fresh_class.new(model).serializable_hash
        expect(res).not_to 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)
          expect(presenter.serializable_hash).to eq(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)
          expect(presenter.serializable_hash).to eq(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)
          expect(presenter.serializable_hash).to eq(name: 'abc', embedded: { a: nil, b: { abc: 'def' } })
        end
      end

      context '#attr_path' do
        it 'for all kinds of attributes' do
          module EntitySpec
            class EmailEntity < Grape::Entity
              expose(:email, as: :addr) { |_, o| o[:attr_path].join('/') }
            end

            class UserEntity < Grape::Entity
              expose(:name, as: :full_name) { |_, o| o[:attr_path].join('/') }
              expose :email, using: 'EntitySpec::EmailEntity'
            end

            class ExtraEntity < Grape::Entity
              expose(:key) { |_, o| o[:attr_path].join('/') }
              expose(:value) { |_, o| o[:attr_path].join('/') }
            end

            class NestedEntity < Grape::Entity
              expose(:name) { |_, o| o[:attr_path].join('/') }
              expose :data, using: 'EntitySpec::ExtraEntity'
            end
          end

          fresh_class.class_eval do
            expose(:id) { |_, o| o[:attr_path].join('/') }
            expose(:foo, as: :bar) { |_, o| o[:attr_path].join('/') }
            expose :title do
              expose :full do
                expose(:prefix, as: :pref) { |_, o| o[:attr_path].join('/') }
                expose(:main) { |_, o| o[:attr_path].join('/') }
              end
            end
            expose :friends, as: :social, using: 'EntitySpec::UserEntity'
            expose :extra, using: 'EntitySpec::ExtraEntity'
            expose :nested, using: 'EntitySpec::NestedEntity'
          end

          expect(subject.serializable_hash).to eq(
            id: 'id',
            bar: 'bar',
            title: { full: { pref: 'title/full/pref', main: 'title/full/main' } },
            social: [
              { full_name: 'social/full_name', email: { addr: 'social/email/addr' } },
              { full_name: 'social/full_name', email: { addr: 'social/email/addr' } }
            ],
            extra: { key: 'extra/key', value: 'extra/value' },
            nested: [
              { name: 'nested/name', data: { key: 'nested/data/key', value: 'nested/data/value' } },
              { name: 'nested/name', data: { key: 'nested/data/key', value: 'nested/data/value' } }
            ]
          )
        end

        it 'allows customize path of an attribute' do
          module EntitySpec
            class CharacterEntity < Grape::Entity
              expose(:key) { |_, o| o[:attr_path].join('/') }
              expose(:value) { |_, o| o[:attr_path].join('/') }
            end
          end

          fresh_class.class_eval do
            expose :characteristics, using: EntitySpec::CharacterEntity,
                                     attr_path: ->(_obj, _opts) { :character }
          end

          expect(subject.serializable_hash).to eq(
            characteristics: [
              { key: 'character/key', value: 'character/value' }
            ]
          )
        end

        it 'can drop one nest level by set path_for to nil' do
          module EntitySpec
            class NoPathCharacterEntity < Grape::Entity
              expose(:key) { |_, o| o[:attr_path].join('/') }
              expose(:value) { |_, o| o[:attr_path].join('/') }
            end
          end

          fresh_class.class_eval do
            expose :characteristics, using: EntitySpec::NoPathCharacterEntity, attr_path: proc {}
          end

          expect(subject.serializable_hash).to eq(
            characteristics: [
              { key: 'key', value: 'value' }
            ]
          )
        end
      end

      context 'with projections passed in options' do
        it 'allows to pass different :only and :except params using the same instance' do
          fresh_class.expose :a, :b, :c
          presenter = fresh_class.new(a: 1, b: 2, c: 3)
          expect(presenter.serializable_hash(only: %i[a b])).to eq(a: 1, b: 2)
          expect(presenter.serializable_hash(only: %i[b c])).to eq(b: 2, c: 3)
        end
      end
    end

    describe '#inspect' do
      before do
        fresh_class.class_eval do
          expose :name, :email
        end
      end

      it 'does not serialize delegator or options' do
        data = subject.inspect
        expect(data).to include 'name='
        expect(data).to include 'email='
        expect(data).to_not include '@options'
        expect(data).to_not include '@delegator'
      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: ->(f) { f.reverse }
        end
      end

      it 'passes through bare expose attributes' do
        expect(subject.value_for(:name)).to eq attributes[:name]
      end

      it 'instantiates a representation if that is called for' do
        rep = subject.value_for(:friends)
        expect(rep.reject { |r| r.is_a?(fresh_class) }).to be_empty
        expect(rep.first.serializable_hash[:name]).to eq 'Friend 1'
        expect(rep.last.serializable_hash[:name]).to eq 'Friend 2'
      end

      context 'child representations' do
        after { EntitySpec::FriendEntity.unexpose_all }

        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.value_for(:friends)
          expect(rep).to be_kind_of Array
          expect(rep.reject { |r| r.is_a?(EntitySpec::FriendEntity) }).to be_empty
          expect(rep.first.serializable_hash[:name]).to eq 'Friend 1'
          expect(rep.last.serializable_hash[:name]).to eq '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, _opts|
              user.friends
            end
          end

          rep = subject.value_for(:custom_friends)
          expect(rep).to be_kind_of Array
          expect(rep.reject { |r| r.is_a?(EntitySpec::FriendEntity) }).to be_empty
          expect(rep.first.serializable_hash).to eq(name: 'Friend 1', email: 'friend1@example.com')
          expect(rep.last.serializable_hash).to eq(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, _opts|
              user.friends.first
            end
          end

          rep = subject.value_for(:first_friend)
          expect(rep).to be_kind_of EntitySpec::FriendEntity
          expect(rep.serializable_hash).to eq(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

          # rubocop:disable Lint/EmptyBlock
          fresh_class.class_eval do
            expose :first_friend, using: EntitySpec::FriendEntity do |_user, _opts|
            end
          end
          # rubocop:enable Lint/EmptyBlock

          rep = subject.value_for(:first_friend)
          expect(rep).to be_kind_of EntitySpec::FriendEntity
          expect(rep.serializable_hash).to be_nil
        end

        it 'passes through exposed entity with key and value attributes' do
          module EntitySpec
            class CharacteristicsEntity < Grape::Entity
              root 'characteristics', 'characteristic'
              expose :key, :value
            end
          end

          fresh_class.class_eval do
            expose :characteristics, using: EntitySpec::CharacteristicsEntity
          end

          rep = subject.value_for(:characteristics)
          expect(rep).to be_kind_of Array
          expect(rep.reject { |r| r.is_a?(EntitySpec::CharacteristicsEntity) }).to be_empty
          expect(rep.first.serializable_hash[:key]).to eq 'hair_color'
          expect(rep.first.serializable_hash[:value]).to eq 'brown'
        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.value_for(:friends)
          expect(rep).to be_kind_of Array
          expect(rep.reject { |r| r.is_a?(EntitySpec::FriendEntity) }).to be_empty
          expect(rep.first.serializable_hash[:email]).to be_nil
          expect(rep.last.serializable_hash[:email]).to be_nil

          rep = subject.value_for(:friends, Grape::Entity::Options.new(user_type: :admin))
          expect(rep).to be_kind_of Array
          expect(rep.reject { |r| r.is_a?(EntitySpec::FriendEntity) }).to be_empty
          expect(rep.first.serializable_hash[:email]).to eq 'friend1@example.com'
          expect(rep.last.serializable_hash[:email]).to eq '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.value_for(:friends, Grape::Entity::Options.new(collection: false))
          expect(rep).to be_kind_of Array
          expect(rep.reject { |r| r.is_a?(EntitySpec::FriendEntity) }).to be_empty
          expect(rep.first.serializable_hash[:email]).to eq 'friend1@example.com'
          expect(rep.last.serializable_hash[:email]).to eq 'friend2@example.com'
        end
      end

      it 'calls through to the proc if there is one' do
        expect(subject.value_for(:computed, Grape::Entity::Options.new(awesome: 123))).to eq 123
      end

      it 'returns a formatted value if format_with is passed' do
        expect(subject.value_for(:birthday)).to eq '02/27/2012'
      end

      it 'returns a formatted value if format_with is passed a lambda' do
        expect(subject.value_for(:fantasies)).to eq ['Nessy', 'Double Rainbows', 'Unicorns']
      end

      context 'delegate_attribute' do
        module EntitySpec
          class DelegatingEntity < Grape::Entity
            root 'friends', 'friend'
            expose :name
            expose :email
            expose :system

            private

            def name
              'cooler name'
            end
          end
        end

        it 'tries instance methods on the entity first' do
          friend = double('Friend', name: 'joe', email: 'joe@example.com')
          rep = EntitySpec::DelegatingEntity.new(friend)
          expect(rep.value_for(:name)).to eq 'cooler name'
          expect(rep.value_for(:email)).to eq 'joe@example.com'

          another_friend = double('Friend', email: 'joe@example.com')
          rep = EntitySpec::DelegatingEntity.new(another_friend)
          expect(rep.value_for(:name)).to eq 'cooler name'
        end

        it 'does not delegate Kernel methods' do
          foo = double 'Foo', system: 'System'
          rep = EntitySpec::DelegatingEntity.new foo
          expect(rep.value_for(:system)).to eq 'System'
        end

        module EntitySpec
          class DerivedEntity < DelegatingEntity
          end
        end

        it 'derived entity get methods from base entity' do
          foo = double 'Foo', name: 'joe'
          rep = EntitySpec::DerivedEntity.new foo
          expect(rep.value_for(:name)).to eq 'cooler name'
        end
      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.value_for(:friends)
          expect(rep).to be_kind_of Array
          expect(rep.size).to eq 2
          expect(rep.all? { |r| r.is_a?(EntitySpec::UserEntity) }).to be true
        end

        it 'class' do
          fresh_class.class_eval do
            expose :friends, using: EntitySpec::UserEntity
          end

          rep = subject.value_for(:friends)
          expect(rep).to be_kind_of Array
          expect(rep.size).to eq 2
          expect(rep.all? { |r| r.is_a?(EntitySpec::UserEntity) }).to be true
        end
      end
    end

    describe '.documentation' do
      it 'returns an empty hash is no documentation is provided' do
        fresh_class.expose :name

        expect(subject.documentation).to eq({})
      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

        expect(subject.documentation).to eq(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

        expect(subject.documentation).to eq(label: doc, email: doc)
      end

      it 'resets memoization when exposing additional attributes' do
        fresh_class.expose :x, documentation: { desc: 'just x' }
        expect(fresh_class.instance_variable_get(:@documentation)).to be_nil
        doc1 = fresh_class.documentation
        expect(fresh_class.instance_variable_get(:@documentation)).not_to be_nil
        fresh_class.expose :y, documentation: { desc: 'just y' }
        expect(fresh_class.instance_variable_get(:@documentation)).to be_nil
        doc2 = fresh_class.documentation
        expect(doc1).to eq(x: { desc: 'just x' })
        expect(doc2).to eq(x: { desc: 'just x' }, y: { desc: 'just y' })
      end

      context 'inherited documentation' do
        it 'returns documentation from ancestor' do
          doc = { type: 'foo', desc: 'bar' }
          fresh_class.expose :name, documentation: doc
          child_class = Class.new(fresh_class)
          child_class.expose :email, documentation: doc

          expect(fresh_class.documentation).to eq(name: doc)
          expect(child_class.documentation).to eq(name: doc, email: doc)
        end

        it 'obeys unexposed attributes in subclass' do
          doc = { type: 'foo', desc: 'bar' }
          fresh_class.expose :name, documentation: doc
          fresh_class.expose :email, documentation: doc
          child_class = Class.new(fresh_class)
          child_class.unexpose :email

          expect(fresh_class.documentation).to eq(name: doc, email: doc)
          expect(child_class.documentation).to eq(name: doc)
        end

        it 'obeys re-exposed attributes in subclass' do
          doc = { type: 'foo', desc: 'bar' }
          fresh_class.expose :name, documentation: doc
          fresh_class.expose :email, documentation: doc

          child_class = Class.new(fresh_class)
          child_class.unexpose :email

          nephew_class = Class.new(child_class)
          new_doc = { type: 'todler', descr: '???' }
          nephew_class.expose :email, documentation: new_doc

          expect(fresh_class.documentation).to eq(name: doc, email: doc)
          expect(child_class.documentation).to eq(name: doc)
          expect(nephew_class.documentation).to eq(name: doc, email: new_doc)
        end

        it 'includes only root exposures' do
          fresh_class.expose :name, documentation: { desc: 'foo' }
          fresh_class.expose :nesting do
            fresh_class.expose :smth, documentation: { desc: 'should not be seen' }
          end
          expect(fresh_class.documentation).to eq(name: { desc: 'foo' })
        end
      end
    end

    describe '::DSL' do
      subject { Class.new }

      it 'creates an Entity class when called' do
        expect(subject).not_to be_const_defined :Entity
        subject.send(:include, Grape::Entity::DSL)
        expect(subject).to be_const_defined :Entity
      end

      context 'pre-mixed' do
        before { subject.send(:include, Grape::Entity::DSL) }

        it 'is able to define entity traits through DSL' do
          subject.entity do
            expose :name
          end

          expect(subject.entity_class.root_exposures).not_to be_empty
        end

        it 'is able to expose straight from the class' do
          subject.entity :name, :email
          expect(subject.entity_class.root_exposures.size).to eq 2
        end

        it 'is able to mix field and advanced.root_exposures' do
          subject.entity :name, :email do
            expose :third
          end
          expect(subject.entity_class.root_exposures.size).to eq 3
        end

        context 'instance' do
          let(:instance) { subject.new }

          describe '#entity' do
            it 'is an instance of the entity class' do
              expect(instance.entity).to be_kind_of(subject.entity_class)
            end

            it 'has an object of itself' do
              expect(instance.entity.object).to eq instance
            end

            it 'instantiates with options if provided' do
              expect(instance.entity(awesome: true).options).to eq(awesome: true)
            end
          end
        end
      end
    end
  end
end