File: api_spec.rb

package info (click to toggle)
ruby-grape 1.6.2-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 2,156 kB
  • sloc: ruby: 25,265; makefile: 7
file content (4349 lines) | stat: -rw-r--r-- 121,841 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
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
# frozen_string_literal: true

require 'spec_helper'
require 'shared/versioning_examples'

describe Grape::API do
  subject do
    puts described_class
    Class.new(described_class)
  end

  def app
    subject
  end

  describe '.prefix' do
    it 'routes root through with the prefix' do
      subject.prefix 'awesome/sauce'
      subject.get do
        'Hello there.'
      end

      get 'awesome/sauce/'
      expect(last_response.status).to be 200
      expect(last_response.body).to eql 'Hello there.'
    end

    it 'routes through with the prefix' do
      subject.prefix 'awesome/sauce'
      subject.get :hello do
        'Hello there.'
      end

      get 'awesome/sauce/hello'
      expect(last_response.body).to eql 'Hello there.'

      get '/hello'
      expect(last_response.status).to be 404
    end

    it 'supports OPTIONS' do
      subject.prefix 'awesome/sauce'
      subject.get do
        'Hello there.'
      end

      options 'awesome/sauce'
      expect(last_response.status).to be 204
      expect(last_response.body).to be_blank
    end

    it 'disallows POST' do
      subject.prefix 'awesome/sauce'
      subject.get

      post 'awesome/sauce'
      expect(last_response.status).to be 405
    end
  end

  describe '.version' do
    context 'when defined' do
      it 'returns version value' do
        subject.version 'v1'
        expect(subject.version).to eq('v1')
      end
    end

    context 'when not defined' do
      it 'returns nil' do
        expect(subject.version).to be_nil
      end
    end
  end

  describe '.version using path' do
    it_behaves_like 'versioning' do
      let(:macro_options) do
        {
          using: :path
        }
      end
    end
  end

  describe '.version using param' do
    it_behaves_like 'versioning' do
      let(:macro_options) do
        {
          using: :param,
          parameter: 'apiver'
        }
      end
    end
  end

  describe '.version using header' do
    it_behaves_like 'versioning' do
      let(:macro_options) do
        {
          using: :header,
          vendor: 'mycompany',
          format: 'json'
        }
      end
    end

    # Behavior as defined by rfc2616 when no header is defined
    # http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
    describe 'no specified accept header' do
      # subject.version 'v1', using: :header
      # subject.get '/hello' do
      #   'hello'
      # end

      # it 'routes' do
      #   get '/hello'
      #   last_response.status.should eql 200
      # end
    end

    # pending 'routes if any media type is allowed'
  end

  describe '.version using accept_version_header' do
    it_behaves_like 'versioning' do
      let(:macro_options) do
        {
          using: :accept_version_header
        }
      end
    end
  end

  describe '.represent' do
    it 'requires a :with option' do
      expect { subject.represent Object, {} }.to raise_error(Grape::Exceptions::InvalidWithOptionForRepresent)
    end

    it 'adds the association to the :representations setting' do
      klass = Class.new
      subject.represent Object, with: klass
      expect(subject.namespace_stackable_with_hash(:representations)[Object]).to eq(klass)
    end
  end

  describe '.namespace' do
    it 'is retrievable and converted to a path' do
      internal_namespace = nil
      subject.namespace :awesome do
        internal_namespace = namespace
      end
      expect(internal_namespace).to eql('/awesome')
    end

    it 'comes after the prefix and version' do
      subject.prefix :rad
      subject.version 'v1', using: :path

      subject.namespace :awesome do
        get('/hello') { 'worked' }
      end

      get '/rad/v1/awesome/hello'
      expect(last_response.body).to eq('worked')
    end

    it 'cancels itself after the block is over' do
      internal_namespace = nil
      subject.namespace :awesome do
        internal_namespace = namespace
      end
      expect(subject.namespace).to eql('/')
    end

    it 'is stackable' do
      internal_namespace = nil
      internal_second_namespace = nil
      subject.namespace :awesome do
        internal_namespace = namespace
        namespace :rad do
          internal_second_namespace = namespace
        end
      end
      expect(internal_namespace).to eq('/awesome')
      expect(internal_second_namespace).to eq('/awesome/rad')
    end

    it 'accepts path segments correctly' do
      inner_namespace = nil
      subject.namespace :members do
        namespace '/:member_id' do
          inner_namespace = namespace
          get '/' do
            params[:member_id]
          end
        end
      end
      get '/members/23'
      expect(last_response.body).to eq('23')
      expect(inner_namespace).to eq('/members/:member_id')
    end

    it 'is callable with nil just to push onto the stack' do
      subject.namespace do
        version 'v2', using: :path
        get('/hello') { 'inner' }
      end
      subject.get('/hello') { 'outer' }

      get '/v2/hello'
      expect(last_response.body).to eq('inner')
      get '/hello'
      expect(last_response.body).to eq('outer')
    end

    %w[group resource resources segment].each do |als|
      it "`.#{als}` is an alias" do
        inner_namespace = nil
        subject.send(als, :awesome) do
          inner_namespace = namespace
        end
        expect(inner_namespace).to eq '/awesome'
      end
    end
  end

  describe '.call' do
    context 'it does not add to the app setup' do
      it 'calls the app' do
        expect(subject).not_to receive(:add_setup)
        subject.call({})
      end
    end
  end

  describe '.route_param' do
    it 'adds a parameterized route segment namespace' do
      subject.namespace :users do
        route_param :id do
          get do
            params[:id]
          end
        end
      end

      get '/users/23'
      expect(last_response.body).to eq('23')
    end

    it 'defines requirements with a single hash' do
      subject.namespace :users do
        route_param :id, requirements: /[0-9]+/ do
          get do
            params[:id]
          end
        end
      end

      get '/users/michael'
      expect(last_response.status).to eq(404)
      get '/users/23'
      expect(last_response.status).to eq(200)
    end

    context 'with param type definitions' do
      it 'is used by passing to options' do
        subject.namespace :route_param do
          route_param :foo, type: Integer do
            get { params.to_json }
          end
        end
        get '/route_param/1234'
        expect(last_response.body).to eq('{"foo":1234}')
      end
    end
  end

  describe '.route' do
    it 'allows for no path' do
      subject.namespace :votes do
        get do
          'Votes'
        end
        post do
          'Created a Vote'
        end
      end

      get '/votes'
      expect(last_response.body).to eql 'Votes'
      post '/votes'
      expect(last_response.body).to eql 'Created a Vote'
    end

    it 'handles empty calls' do
      subject.get '/'
      get '/'
      expect(last_response.body).to eql ''
    end

    describe 'root routes should work with' do
      before do
        subject.format :txt
        subject.content_type :json, 'application/json'
        subject.formatter :json, ->(object, _env) { object }
        def subject.enable_root_route!
          get('/') { 'root' }
        end
      end

      after do
        expect(last_response.body).to eql 'root'
      end

      describe 'path versioned APIs' do
        before do
          subject.version version, using: :path
          subject.enable_root_route!
        end

        context 'when a single version provided' do
          let(:version) { 'v1' }

          it 'without a format' do
            versioned_get '/', 'v1', using: :path
          end

          it 'with a format' do
            get '/v1/.json'
          end
        end

        context 'when array of versions provided' do
          let(:version) { %w[v1 v2] }

          it { versioned_get '/', 'v1', using: :path }
          it { versioned_get '/', 'v2', using: :path }
        end
      end

      it 'header versioned APIs' do
        subject.version 'v1', using: :header, vendor: 'test'
        subject.enable_root_route!

        versioned_get '/', 'v1', using: :header, vendor: 'test'
      end

      it 'header versioned APIs with multiple headers' do
        subject.version %w[v1 v2], using: :header, vendor: 'test'
        subject.enable_root_route!

        versioned_get '/', 'v1', using: :header, vendor: 'test'
        versioned_get '/', 'v2', using: :header, vendor: 'test'
      end

      it 'param versioned APIs' do
        subject.version 'v1', using: :param
        subject.enable_root_route!

        versioned_get '/', 'v1', using: :param
      end

      it 'Accept-Version header versioned APIs' do
        subject.version 'v1', using: :accept_version_header
        subject.enable_root_route!

        versioned_get '/', 'v1', using: :accept_version_header
      end

      it 'unversioned APIs' do
        subject.enable_root_route!

        get '/'
      end
    end

    it 'allows for multiple paths' do
      subject.get(['/abc', '/def']) do
        'foo'
      end

      get '/abc'
      expect(last_response.body).to eql 'foo'
      get '/def'
      expect(last_response.body).to eql 'foo'
    end

    context 'format' do
      module ApiSpec
        class DummyFormatClass
        end
      end

      before do
        allow_any_instance_of(ApiSpec::DummyFormatClass).to receive(:to_json).and_return('abc')
        allow_any_instance_of(ApiSpec::DummyFormatClass).to receive(:to_txt).and_return('def')

        subject.get('/abc') do
          ApiSpec::DummyFormatClass.new
        end
      end

      it 'allows .json' do
        get '/abc.json'
        expect(last_response.status).to eq(200)
        expect(last_response.body).to eql 'abc' # json-encoded symbol
      end

      it 'allows .txt' do
        get '/abc.txt'
        expect(last_response.status).to eq(200)
        expect(last_response.body).to eql 'def' # raw text
      end
    end

    it 'allows for format without corrupting a param' do
      subject.get('/:id') do
        { 'id' => params[:id] }
      end

      get '/awesome.json'
      expect(last_response.body).to eql '{"id":"awesome"}'
    end

    it 'allows for format in namespace with no path' do
      subject.namespace :abc do
        get do
          ['json']
        end
      end

      get '/abc.json'
      expect(last_response.body).to eql '["json"]'
    end

    it 'allows for multiple verbs' do
      subject.route(%i[get post], '/abc') do
        'hiya'
      end

      subject.endpoints.first.routes.each do |route|
        expect(route.path).to eql '/abc(.:format)'
      end

      get '/abc'
      expect(last_response.body).to eql 'hiya'
      post '/abc'
      expect(last_response.body).to eql 'hiya'
    end

    %i[put post].each do |verb|
      context verb.to_s do
        ['string', :symbol, 1, -1.1, {}, [], true, false, nil].each do |object|
          it "allows a(n) #{object.class} json object in params" do
            subject.format :json
            subject.send(verb) do
              env['api.request.body']
            end
            send verb, '/', ::Grape::Json.dump(object), 'CONTENT_TYPE' => 'application/json'
            expect(last_response.status).to eq(verb == :post ? 201 : 200)
            expect(last_response.body).to eql ::Grape::Json.dump(object)
            expect(last_request.params).to eql({})
          end

          it 'stores input in api.request.input' do
            subject.format :json
            subject.send(verb) do
              env['api.request.input']
            end
            send verb, '/', ::Grape::Json.dump(object), 'CONTENT_TYPE' => 'application/json'
            expect(last_response.status).to eq(verb == :post ? 201 : 200)
            expect(last_response.body).to eql ::Grape::Json.dump(object).to_json
          end

          context 'chunked transfer encoding' do
            it 'stores input in api.request.input' do
              subject.format :json
              subject.send(verb) do
                env['api.request.input']
              end
              send verb, '/', ::Grape::Json.dump(object), 'CONTENT_TYPE' => 'application/json', 'HTTP_TRANSFER_ENCODING' => 'chunked', 'CONTENT_LENGTH' => nil
              expect(last_response.status).to eq(verb == :post ? 201 : 200)
              expect(last_response.body).to eql ::Grape::Json.dump(object).to_json
            end
          end
        end
      end
    end

    it 'allows for multipart paths' do
      subject.route(%i[get post], '/:id/first') do
        'first'
      end

      subject.route(%i[get post], '/:id') do
        'ola'
      end
      subject.route(%i[get post], '/:id/first/second') do
        'second'
      end

      get '/1'
      expect(last_response.body).to eql 'ola'
      post '/1'
      expect(last_response.body).to eql 'ola'
      get '/1/first'
      expect(last_response.body).to eql 'first'
      post '/1/first'
      expect(last_response.body).to eql 'first'
      get '/1/first/second'
      expect(last_response.body).to eql 'second'
    end

    it 'allows for :any as a verb' do
      subject.route(:any, '/abc') do
        'lol'
      end

      %w[get post put delete options patch].each do |m|
        send(m, '/abc')
        expect(last_response.body).to eql 'lol'
      end
    end

    it 'allows for catch-all in a namespace' do
      subject.namespace :nested do
        get do
          'root'
        end

        get 'something' do
          'something'
        end

        route :any, '*path' do
          'catch-all'
        end
      end

      get 'nested'
      expect(last_response.body).to eql 'root'

      get 'nested/something'
      expect(last_response.body).to eql 'something'

      get 'nested/missing'
      expect(last_response.body).to eql 'catch-all'

      post 'nested'
      expect(last_response.body).to eql 'catch-all'

      post 'nested/something'
      expect(last_response.body).to eql 'catch-all'
    end

    verbs = %w[post get head delete put options patch]
    verbs.each do |verb|
      it "allows and properly constrain a #{verb.upcase} method" do
        subject.send(verb, '/example') do
          verb
        end
        send(verb, '/example')
        expect(last_response.body).to eql verb == 'head' ? '' : verb
        # Call it with all methods other than the properly constrained one.
        (verbs - [verb]).each do |other_verb|
          send(other_verb, '/example')
          expected_rc = if other_verb == 'options' then 204
                        elsif other_verb == 'head' && verb == 'get' then 200
                        else
                          405
                        end
          expect(last_response.status).to eql expected_rc
        end
      end
    end

    it 'returns a 201 response code for POST by default' do
      subject.post('example') do
        'Created'
      end

      post '/example'
      expect(last_response.status).to be 201
      expect(last_response.body).to eql 'Created'
    end

    it 'returns a 405 for an unsupported method with an X-Custom-Header' do
      subject.before { header 'X-Custom-Header', 'foo' }
      subject.get 'example' do
        'example'
      end
      put '/example'
      expect(last_response.status).to be 405
      expect(last_response.body).to eql '405 Not Allowed'
      expect(last_response.headers['X-Custom-Header']).to eql 'foo'
    end

    it 'runs only the before filter on 405 bad method' do
      subject.namespace :example do
        before            { header 'X-Custom-Header', 'foo' }

        before_validation { raise 'before_validation filter should not run' }
        after_validation  { raise 'after_validation filter should not run' }
        after             { raise 'after filter should not run' }

        params { requires :only_for_get }
        get
      end

      post '/example'
      expect(last_response.status).to be 405
      expect(last_response.headers['X-Custom-Header']).to eql 'foo'
    end

    it 'runs before filter exactly once on 405 bad method' do
      already_run = false
      subject.namespace :example do
        before do
          raise 'before filter ran twice' if already_run

          already_run = true
          header 'X-Custom-Header', 'foo'
        end

        get
      end

      post '/example'
      expect(last_response.status).to be 405
      expect(last_response.headers['X-Custom-Header']).to eql 'foo'
    end

    it 'runs all filters and body with a custom OPTIONS method' do
      subject.namespace :example do
        before            { header 'X-Custom-Header-1', 'foo' }

        before_validation { header 'X-Custom-Header-2', 'foo' }
        after_validation  { header 'X-Custom-Header-3', 'foo' }
        after             { header 'X-Custom-Header-4', 'foo' }

        options { 'yup' }
        get
      end

      options '/example'
      expect(last_response.status).to be 200
      expect(last_response.body).to eql 'yup'
      expect(last_response.headers['Allow']).to be_nil
      expect(last_response.headers['X-Custom-Header-1']).to eql 'foo'
      expect(last_response.headers['X-Custom-Header-2']).to eql 'foo'
      expect(last_response.headers['X-Custom-Header-3']).to eql 'foo'
      expect(last_response.headers['X-Custom-Header-4']).to eql 'foo'
    end

    context 'when format is xml' do
      it 'returns a 405 for an unsupported method' do
        subject.format :xml
        subject.get 'example' do
          'example'
        end

        put '/example'
        expect(last_response.status).to be 405
        expect(last_response.body).to eq <<~XML
          <?xml version="1.0" encoding="UTF-8"?>
          <error>
            <message>405 Not Allowed</message>
          </error>
        XML
      end
    end

    context 'when accessing env' do
      it 'returns a 405 for an unsupported method' do
        subject.before do
          _customheader1 = headers['X-Custom-Header']
          _customheader2 = env['HTTP_X_CUSTOM_HEADER']
        end
        subject.get 'example' do
          'example'
        end
        put '/example'
        expect(last_response.status).to be 405
        expect(last_response.body).to eql '405 Not Allowed'
      end
    end

    specify '405 responses includes an Allow header specifying supported methods' do
      subject.get 'example' do
        'example'
      end
      subject.post 'example' do
        'example'
      end
      put '/example'
      expect(last_response.headers['Allow']).to eql 'OPTIONS, GET, POST, HEAD'
    end

    specify '405 responses includes an Content-Type header' do
      subject.get 'example' do
        'example'
      end
      subject.post 'example' do
        'example'
      end
      put '/example'
      expect(last_response.headers['Content-Type']).to eql 'text/plain'
    end

    describe 'adds an OPTIONS route that' do
      before do
        subject.before            { header 'X-Custom-Header', 'foo' }
        subject.before_validation { header 'X-Custom-Header-2', 'bar' }
        subject.after_validation  { header 'X-Custom-Header-3', 'baz' }
        subject.after             { header 'X-Custom-Header-4', 'bing' }
        subject.params { requires :only_for_get }
        subject.get 'example' do
          'example'
        end
        subject.route :any, '*path' do
          error! :not_found, 404
        end
        options '/example'
      end

      it 'returns a 204' do
        expect(last_response.status).to be 204
      end

      it 'has an empty body' do
        expect(last_response.body).to be_blank
      end

      it 'has an Allow header' do
        expect(last_response.headers['Allow']).to eql 'OPTIONS, GET, HEAD'
      end

      it 'calls before hook' do
        expect(last_response.headers['X-Custom-Header']).to eql 'foo'
      end

      it 'does not call before_validation hook' do
        expect(last_response.headers.key?('X-Custom-Header-2')).to be false
      end

      it 'does not call after_validation hook' do
        expect(last_response.headers.key?('X-Custom-Header-3')).to be false
      end

      it 'calls after hook' do
        expect(last_response.headers['X-Custom-Header-4']).to eq 'bing'
      end

      it 'has no Content-Type' do
        expect(last_response.content_type).to be_nil
      end

      it 'has no Content-Length' do
        expect(last_response.content_length).to be_nil
      end
    end

    describe 'when a resource routes by POST, GET, PATCH, PUT, and DELETE' do
      before do
        subject.namespace :example do
          get do
            'example'
          end

          patch do
            'example'
          end

          post do
            'example'
          end

          delete do
            'example'
          end

          put do
            'example'
          end
        end
        options '/example'
      end

      describe 'it adds an OPTIONS route for namespaced endpoints that' do
        it 'returns a 204' do
          expect(last_response.status).to be 204
        end

        it 'has an empty body' do
          expect(last_response.body).to be_blank
        end

        it 'has an Allow header' do
          expect(last_response.headers['Allow']).to eql 'OPTIONS, GET, PATCH, POST, DELETE, PUT, HEAD'
        end
      end
    end

    describe 'adds an OPTIONS route for namespaced endpoints that' do
      before do
        subject.before { header 'X-Custom-Header', 'foo' }
        subject.namespace :example do
          before { header 'X-Custom-Header-2', 'foo' }

          get :inner do
            'example/inner'
          end
        end
        options '/example/inner'
      end

      it 'returns a 204' do
        expect(last_response.status).to be 204
      end

      it 'has an empty body' do
        expect(last_response.body).to be_blank
      end

      it 'has an Allow header' do
        expect(last_response.headers['Allow']).to eql 'OPTIONS, GET, HEAD'
      end

      it 'calls the outer before filter' do
        expect(last_response.headers['X-Custom-Header']).to eql 'foo'
      end

      it 'calls the inner before filter' do
        expect(last_response.headers['X-Custom-Header-2']).to eql 'foo'
      end

      it 'has no Content-Type' do
        expect(last_response.content_type).to be_nil
      end

      it 'has no Content-Length' do
        expect(last_response.content_length).to be_nil
      end
    end

    describe 'adds a 405 Not Allowed route that' do
      before do
        subject.before { header 'X-Custom-Header', 'foo' }
        subject.post :example do
          'example'
        end
        get '/example'
      end

      it 'returns a 405' do
        expect(last_response.status).to be 405
      end

      it 'contains error message in body' do
        expect(last_response.body).to eq '405 Not Allowed'
      end

      it 'has an Allow header' do
        expect(last_response.headers['Allow']).to eql 'OPTIONS, POST'
      end

      it 'has a X-Custom-Header' do
        expect(last_response.headers['X-Custom-Header']).to eql 'foo'
      end
    end

    describe 'when hook behaviour is controlled by attributes on the route' do
      before do
        subject.before do
          error!('Access Denied', 401) unless route.options[:secret] == params[:secret]
        end

        subject.namespace 'example' do
          before do
            error!('Access Denied', 401) unless route.options[:namespace_secret] == params[:namespace_secret]
          end

          desc 'it gets with secret', secret: 'password'
          get { status(params[:id] == '504' ? 200 : 404) }

          desc 'it post with secret', secret: 'password', namespace_secret: 'namespace_password'
          post {}
        end
      end

      context 'when HTTP method is not defined' do
        let(:response) { delete('/example') }

        it 'responds with a 405 status' do
          expect(response.status).to be 405
        end
      end

      context 'when HTTP method is defined with attribute' do
        let(:response) { post('/example?secret=incorrect_password') }

        it 'responds with the defined error in the before hook' do
          expect(response.status).to be 401
        end
      end

      context 'when HTTP method is defined and the underlying before hook expectation is not met' do
        let(:response) { post('/example?secret=password&namespace_secret=wrong_namespace_password') }

        it 'ends up in the endpoint' do
          expect(response.status).to be 401
        end
      end

      context 'when HTTP method is defined and everything is like the before hooks expect' do
        let(:response) { post('/example?secret=password&namespace_secret=namespace_password') }

        it 'ends up in the endpoint' do
          expect(response.status).to be 201
        end
      end

      context 'when HEAD is called for the defined GET' do
        let(:response) { head('/example?id=504') }

        it 'responds with 401 because before expectations in before hooks are not met' do
          expect(response.status).to be 401
        end
      end

      context 'when HEAD is called for the defined GET' do
        let(:response) { head('/example?id=504&secret=password') }

        it 'responds with 200 because before hooks are not called' do
          expect(response.status).to be 200
        end
      end
    end

    context 'allows HEAD on a GET request that' do
      before do
        subject.get 'example' do
          'example'
        end
        subject.route :any, '*path' do
          error! :not_found, 404
        end
        head '/example'
      end

      it 'returns a 200' do
        expect(last_response.status).to be 200
      end

      it 'has an empty body' do
        expect(last_response.body).to eql ''
      end
    end

    it 'overwrites the default HEAD request' do
      subject.head 'example' do
        error! 'nothing to see here', 400
      end
      subject.get 'example' do
        'example'
      end
      head '/example'
      expect(last_response.status).to be 400
    end
  end

  context 'do_not_route_head!' do
    before do
      subject.do_not_route_head!
      subject.get 'example' do
        'example'
      end
    end

    it 'options does not contain HEAD' do
      options '/example'
      expect(last_response.status).to be 204
      expect(last_response.body).to eql ''
      expect(last_response.headers['Allow']).to eql 'OPTIONS, GET'
    end

    it 'does not allow HEAD on a GET request' do
      head '/example'
      expect(last_response.status).to be 405
    end
  end

  context 'do_not_route_options!' do
    before do
      subject.do_not_route_options!
      subject.get 'example' do
        'example'
      end
    end

    it 'does not create an OPTIONS route' do
      options '/example'
      expect(last_response.status).to be 405
    end

    it 'does not include OPTIONS in Allow header' do
      options '/example'
      expect(last_response.status).to be 405
      expect(last_response.headers['Allow']).to eql 'GET, HEAD'
    end
  end

  describe '.compile!' do
    it 'requires the grape/eager_load file' do
      expect(app).to receive(:require).with('grape/eager_load').and_return(nil)
      app.compile!
    end

    it 'compiles the instance for rack!' do
      stubbed_object = double(:instance_for_rack)
      allow(app).to receive(:instance_for_rack) { stubbed_object }
    end
  end

  # NOTE: this method is required to preserve the ability of pre-mounting
  # the root API into a namespace, it may be deprecated in the future.
  describe 'instance_for_rack' do
    context 'when the app was not mounted' do
      it 'returns the base_instance' do
        expect(app.send(:instance_for_rack)).to eq app.base_instance
      end
    end

    context 'when the app was mounted' do
      it 'returns the first mounted instance' do
        mounted_app = app
        Class.new(described_class) do
          namespace 'new_namespace' do
            mount mounted_app
          end
        end
        expect(app.send(:instance_for_rack)).to eq app.send(:mounted_instances).first
      end
    end
  end

  describe 'filters' do
    it 'adds a before filter' do
      subject.before { @foo = 'first'  }
      subject.before { @bar = 'second' }
      subject.get '/' do
        "#{@foo} #{@bar}"
      end

      get '/'
      expect(last_response.body).to eql 'first second'
    end

    it 'adds a before filter to current and child namespaces only' do
      subject.get '/' do
        "root - #{instance_variable_defined?(:@foo) ? @foo : nil}"
      end
      subject.namespace :blah do
        before { @foo = 'foo' }

        get '/' do
          "blah - #{@foo}"
        end

        namespace :bar do
          get '/' do
            "blah - bar - #{@foo}"
          end
        end
      end

      get '/'
      expect(last_response.body).to eql 'root - '
      get '/blah'
      expect(last_response.body).to eql 'blah - foo'
      get '/blah/bar'
      expect(last_response.body).to eql 'blah - bar - foo'
    end

    it 'adds a after_validation filter' do
      subject.after_validation { @foo = "first #{params[:id]}:#{params[:id].class}" }
      subject.after_validation { @bar = 'second' }
      subject.params do
        requires :id, type: Integer
      end
      subject.get '/' do
        "#{@foo} #{@bar}"
      end

      get '/', id: '32'
      expect(last_response.body).to eql "first 32:#{integer_class_name} second"
    end

    it 'adds a after filter' do
      m = double('after mock')
      subject.after { m.do_something! }
      subject.after { m.do_something! }
      subject.get '/' do
        @var ||= 'default'
      end

      expect(m).to receive(:do_something!).twice
      get '/'
      expect(last_response.body).to eql 'default'
    end

    it 'calls all filters when validation passes' do
      a = double('before mock')
      b = double('before_validation mock')
      c = double('after_validation mock')
      d = double('after mock')

      subject.params do
        requires :id, type: Integer
      end
      subject.resource ':id' do
        before { a.do_something! }

        before_validation { b.do_something! }
        after_validation { c.do_something! }
        after { d.do_something! }

        get do
          'got it'
        end
      end

      expect(a).to receive(:do_something!).once
      expect(b).to receive(:do_something!).once
      expect(c).to receive(:do_something!).once
      expect(d).to receive(:do_something!).once

      get '/123'
      expect(last_response.status).to be 200
      expect(last_response.body).to eql 'got it'
    end

    it 'calls only before filters when validation fails' do
      a = double('before mock')
      b = double('before_validation mock')
      c = double('after_validation mock')
      d = double('after mock')

      subject.params do
        requires :id, type: Integer
      end
      subject.resource ':id' do
        before { a.do_something! }

        before_validation { b.do_something! }
        after_validation { c.do_something! }
        after { d.do_something! }

        get do
          'got it'
        end
      end

      expect(a).to receive(:do_something!).once
      expect(b).to receive(:do_something!).once
      expect(c).to receive(:do_something!).exactly(0).times
      expect(d).to receive(:do_something!).exactly(0).times

      get '/abc'
      expect(last_response.status).to be 400
      expect(last_response.body).to eql 'id is invalid'
    end

    it 'calls filters in the correct order' do
      i = 0
      a = double('before mock')
      b = double('before_validation mock')
      c = double('after_validation mock')
      d = double('after mock')

      subject.params do
        requires :id, type: Integer
      end
      subject.resource ':id' do
        before { a.here(i += 1) }

        before_validation { b.here(i += 1) }
        after_validation { c.here(i += 1) }
        after { d.here(i += 1) }

        get do
          'got it'
        end
      end

      expect(a).to receive(:here).with(1).once
      expect(b).to receive(:here).with(2).once
      expect(c).to receive(:here).with(3).once
      expect(d).to receive(:here).with(4).once

      get '/123'
      expect(last_response.status).to be 200
      expect(last_response.body).to eql 'got it'
    end
  end

  context 'format' do
    before do
      subject.get('/foo') { 'bar' }
    end

    it 'sets content type for txt format' do
      get '/foo'
      expect(last_response.headers['Content-Type']).to eq('text/plain')
    end

    it 'does not set Cache-Control' do
      get '/foo'
      expect(last_response.headers['Cache-Control']).to eq(nil)
    end

    it 'sets content type for xml' do
      get '/foo.xml'
      expect(last_response.headers['Content-Type']).to eq('application/xml')
    end

    it 'sets content type for json' do
      get '/foo.json'
      expect(last_response.headers['Content-Type']).to eq('application/json')
    end

    it 'sets content type for serializable hash format' do
      get '/foo.serializable_hash'
      expect(last_response.headers['Content-Type']).to eq('application/json')
    end

    it 'sets content type for binary format' do
      get '/foo.binary'
      expect(last_response.headers['Content-Type']).to eq('application/octet-stream')
    end

    it 'returns raw data when content type binary' do
      image_filename = 'grape.png'
      file = File.open(image_filename, 'rb', &:read)
      subject.format :binary
      subject.get('/binary_file') { File.binread(image_filename) }
      get '/binary_file'
      expect(last_response.headers['Content-Type']).to eq('application/octet-stream')
      expect(last_response.body).to eq(file)
    end

    it 'returns the content of the file with file' do
      file_content = 'This is some file content'
      test_file = Tempfile.new('test')
      test_file.write file_content
      test_file.rewind

      subject.get('/file') { file test_file }
      get '/file'
      expect(last_response.headers['Content-Length']).to eq('25')
      expect(last_response.headers['Content-Type']).to eq('text/plain')
      expect(last_response.body).to eq(file_content)
    end

    it 'streams the content of the file with stream' do
      test_stream = Enumerator.new do |blk|
        blk.yield 'This is some'
        blk.yield ' file content'
      end

      subject.use Rack::Chunked
      subject.get('/stream') { stream test_stream }
      get '/stream', {}, 'HTTP_VERSION' => 'HTTP/1.1', 'SERVER_PROTOCOL' => 'HTTP/1.1'

      expect(last_response.headers['Content-Type']).to eq('text/plain')
      expect(last_response.headers['Content-Length']).to eq(nil)
      expect(last_response.headers['Cache-Control']).to eq('no-cache')
      expect(last_response.headers['Transfer-Encoding']).to eq('chunked')

      expect(last_response.body).to eq("c\r\nThis is some\r\nd\r\n file content\r\n0\r\n\r\n")
    end

    it 'sets content type for error' do
      subject.get('/error') { error!('error in plain text', 500) }
      get '/error'
      expect(last_response.headers['Content-Type']).to eql 'text/plain'
    end

    it 'sets content type for json error' do
      subject.format :json
      subject.get('/error') { error!('error in json', 500) }
      get '/error.json'
      expect(last_response.status).to be 500
      expect(last_response.headers['Content-Type']).to eql 'application/json'
    end

    it 'sets content type for xml error' do
      subject.format :xml
      subject.get('/error') { error!('error in xml', 500) }
      get '/error'
      expect(last_response.status).to be 500
      expect(last_response.headers['Content-Type']).to eql 'application/xml'
    end

    it 'includes extension in format' do
      subject.get(':id') { params[:format] }

      get '/baz.bar'
      expect(last_response.status).to eq 200
      expect(last_response.body).to eq 'bar'
    end

    it 'does not include extension in id' do
      subject.format :json
      subject.get(':id') { params }

      get '/baz.bar'
      expect(last_response.status).to eq 404
    end

    context 'with a custom content_type' do
      before do
        subject.content_type :custom, 'application/custom'
        subject.formatter :custom, ->(_object, _env) { 'custom' }

        subject.get('/custom') { 'bar' }
        subject.get('/error') { error!('error in custom', 500) }
      end

      it 'sets content type' do
        get '/custom.custom'
        expect(last_response.headers['Content-Type']).to eql 'application/custom'
      end

      it 'sets content type for error' do
        get '/error.custom'
        expect(last_response.headers['Content-Type']).to eql 'application/custom'
      end
    end

    context 'env["api.format"]' do
      before do
        subject.post 'attachment' do
          filename = params[:file][:filename]
          content_type MIME::Types.type_for(filename)[0].to_s
          env['api.format'] = :binary # there's no formatter for :binary, data will be returned "as is"
          header 'Content-Disposition', "attachment; filename*=UTF-8''#{CGI.escape(filename)}"
          params[:file][:tempfile].read
        end
      end

      ['/attachment.png', 'attachment'].each do |url|
        it "uploads and downloads a PNG file via #{url}" do
          image_filename = 'grape.png'
          post url, file: Rack::Test::UploadedFile.new(image_filename, 'image/png', true)
          expect(last_response.status).to eq(201)
          expect(last_response.headers['Content-Type']).to eq('image/png')
          expect(last_response.headers['Content-Disposition']).to eq("attachment; filename*=UTF-8''grape.png")
          File.open(image_filename, 'rb') do |io|
            expect(last_response.body).to eq io.read
          end
        end
      end

      it 'uploads and downloads a Ruby file' do
        filename = __FILE__
        post '/attachment.rb', file: Rack::Test::UploadedFile.new(filename, 'application/x-ruby', true)
        expect(last_response.status).to eq(201)
        expect(last_response.headers['Content-Type']).to eq('application/x-ruby')
        expect(last_response.headers['Content-Disposition']).to eq("attachment; filename*=UTF-8''api_spec.rb")
        File.open(filename, 'rb') do |io|
          expect(last_response.body).to eq io.read
        end
      end
    end
  end

  context 'custom middleware' do
    module ApiSpec
      class PhonyMiddleware
        def initialize(app, *args)
          @args = args
          @app = app
          @block = block_given? ? true : nil
        end

        def call(env)
          env['phony.args'] ||= []
          env['phony.args'] << @args
          env['phony.block'] = true if @block
          @app.call(env)
        end
      end
    end

    describe '.middleware' do
      it 'includes middleware arguments from settings' do
        subject.use ApiSpec::PhonyMiddleware, 'abc', 123
        expect(subject.middleware).to eql [[:use, ApiSpec::PhonyMiddleware, 'abc', 123]]
      end

      it 'includes all middleware from stacked settings' do
        subject.use ApiSpec::PhonyMiddleware, 123
        subject.use ApiSpec::PhonyMiddleware, 'abc'
        subject.use ApiSpec::PhonyMiddleware, 'foo'

        expect(subject.middleware).to eql [
          [:use, ApiSpec::PhonyMiddleware, 123],
          [:use, ApiSpec::PhonyMiddleware, 'abc'],
          [:use, ApiSpec::PhonyMiddleware, 'foo']
        ]
      end
    end

    describe '.use' do
      it 'adds middleware' do
        subject.use ApiSpec::PhonyMiddleware, 123
        expect(subject.middleware).to eql [[:use, ApiSpec::PhonyMiddleware, 123]]
      end

      it 'does not show up outside the namespace' do
        inner_middleware = nil
        subject.use ApiSpec::PhonyMiddleware, 123
        subject.namespace :awesome do
          use ApiSpec::PhonyMiddleware, 'abc'
          inner_middleware = middleware
        end

        expect(subject.middleware).to eql [[:use, ApiSpec::PhonyMiddleware, 123]]
        expect(inner_middleware).to eql [[:use, ApiSpec::PhonyMiddleware, 123], [:use, ApiSpec::PhonyMiddleware, 'abc']]
      end

      it 'calls the middleware' do
        subject.use ApiSpec::PhonyMiddleware, 'hello'
        subject.get '/' do
          env['phony.args'].first.first
        end

        get '/'
        expect(last_response.body).to eql 'hello'
      end

      it 'adds a block if one is given' do
        block = -> {}
        subject.use ApiSpec::PhonyMiddleware, &block
        expect(subject.middleware).to eql [[:use, ApiSpec::PhonyMiddleware, block]]
      end

      it 'uses a block if one is given' do
        block = -> {}
        subject.use ApiSpec::PhonyMiddleware, &block
        subject.get '/' do
          env['phony.block'].inspect
        end

        get '/'
        expect(last_response.body).to eq('true')
      end

      it 'does not destroy the middleware settings on multiple runs' do
        block = -> {}
        subject.use ApiSpec::PhonyMiddleware, &block
        subject.get '/' do
          env['phony.block'].inspect
        end

        2.times do
          get '/'
          expect(last_response.body).to eq('true')
        end
      end

      it 'mounts behind error middleware' do
        m = Class.new(Grape::Middleware::Base) do
          def before
            throw :error, message: 'Caught in the Net', status: 400
          end
        end
        subject.use m
        subject.get '/' do
        end
        get '/'
        expect(last_response.status).to eq(400)
        expect(last_response.body).to eq('Caught in the Net')
      end
    end

    describe '.insert_before' do
      it 'runs before a given middleware' do
        m = Class.new(Grape::Middleware::Base) do
          def call(env)
            env['phony.args'] ||= []
            env['phony.args'] << @options[:message]
            @app.call(env)
          end
        end

        subject.use ApiSpec::PhonyMiddleware, 'hello'
        subject.insert_before ApiSpec::PhonyMiddleware, m, message: 'bye'
        subject.get '/' do
          env['phony.args'].join(' ')
        end

        get '/'
        expect(last_response.body).to eql 'bye hello'
      end
    end

    describe '.insert_after' do
      it 'runs after a given middleware' do
        m = Class.new(Grape::Middleware::Base) do
          def call(env)
            env['phony.args'] ||= []
            env['phony.args'] << @options[:message]
            @app.call(env)
          end
        end

        subject.use ApiSpec::PhonyMiddleware, 'hello'
        subject.insert_after ApiSpec::PhonyMiddleware, m, message: 'bye'
        subject.get '/' do
          env['phony.args'].join(' ')
        end

        get '/'
        expect(last_response.body).to eql 'hello bye'
      end
    end
  end

  describe '.insert' do
    it 'inserts middleware in a specific location in the stack' do
      m = Class.new(Grape::Middleware::Base) do
        def call(env)
          env['phony.args'] ||= []
          env['phony.args'] << @options[:message]
          @app.call(env)
        end
      end

      subject.use ApiSpec::PhonyMiddleware, 'bye'
      subject.insert 0, m, message: 'good'
      subject.insert 0, m, message: 'hello'
      subject.get '/' do
        env['phony.args'].join(' ')
      end

      get '/'
      expect(last_response.body).to eql 'hello good bye'
    end
  end

  describe '.http_basic' do
    it 'protects any resources on the same scope' do
      subject.http_basic do |u, _p|
        u == 'allow'
      end
      subject.get(:hello) { 'Hello, world.' }
      get '/hello'
      expect(last_response.status).to be 401
      get '/hello', {}, 'HTTP_AUTHORIZATION' => encode_basic_auth('allow', 'whatever')
      expect(last_response.status).to be 200
    end

    it 'is scopable' do
      subject.get(:hello) { 'Hello, world.' }
      subject.namespace :admin do
        http_basic do |u, _p|
          u == 'allow'
        end

        get(:hello) { 'Hello, world.' }
      end

      get '/hello'
      expect(last_response.status).to be 200
      get '/admin/hello'
      expect(last_response.status).to be 401
    end

    it 'is callable via .auth as well' do
      subject.auth :http_basic do |u, _p|
        u == 'allow'
      end

      subject.get(:hello) { 'Hello, world.' }
      get '/hello'
      expect(last_response.status).to be 401
      get '/hello', {}, 'HTTP_AUTHORIZATION' => encode_basic_auth('allow', 'whatever')
      expect(last_response.status).to be 200
    end

    it 'has access to the current endpoint' do
      basic_auth_context = nil

      subject.http_basic do |u, _p|
        basic_auth_context = self

        u == 'allow'
      end

      subject.get(:hello) { 'Hello, world.' }
      get '/hello', {}, 'HTTP_AUTHORIZATION' => encode_basic_auth('allow', 'whatever')
      expect(basic_auth_context).to be_a_kind_of(Grape::Endpoint)
    end

    it 'has access to helper methods' do
      subject.helpers do
        def authorize(u, p)
          u == 'allow' && p == 'whatever'
        end
      end

      subject.http_basic do |u, p|
        authorize(u, p)
      end

      subject.get(:hello) { 'Hello, world.' }
      get '/hello', {}, 'HTTP_AUTHORIZATION' => encode_basic_auth('allow', 'whatever')
      expect(last_response.status).to be 200
      get '/hello', {}, 'HTTP_AUTHORIZATION' => encode_basic_auth('disallow', 'whatever')
      expect(last_response.status).to be 401
    end

    it 'can set instance variables accessible to routes' do
      subject.http_basic do |u, _p|
        @hello = 'Hello, world.'

        u == 'allow'
      end

      subject.get(:hello) { @hello }
      get '/hello', {}, 'HTTP_AUTHORIZATION' => encode_basic_auth('allow', 'whatever')
      expect(last_response.status).to be 200
      expect(last_response.body).to eql 'Hello, world.'
    end
  end

  describe '.logger' do
    it 'returns an instance of Logger class by default' do
      expect(subject.logger.class).to eql Logger
    end

    context 'with a custom logger' do
      subject do
        Class.new(described_class) do
          def self.io
            @io ||= StringIO.new
          end
          logger ::Logger.new(io)
        end
      end

      it 'exposes its interaface' do
        message = 'this will be logged'
        subject.logger.info message
        expect(subject.io.string).to include(message)
      end
    end

    it 'does not unnecessarily retain duplicate setup blocks' do
      subject.logger
      expect { subject.logger }.not_to change(subject.instance_variable_get(:@setup), :size)
    end
  end

  describe '.helpers' do
    it 'is accessible from the endpoint' do
      subject.helpers do
        def hello
          'Hello, world.'
        end
      end

      subject.get '/howdy' do
        hello
      end

      get '/howdy'
      expect(last_response.body).to eql 'Hello, world.'
    end

    it 'is scopable' do
      subject.helpers do
        def generic
          'always there'
        end
      end

      subject.namespace :admin do
        helpers do
          def secret
            'only in admin'
          end
        end

        get '/secret' do
          [generic, secret].join ':'
        end
      end

      subject.get '/generic' do
        [generic, respond_to?(:secret)].join ':'
      end

      get '/generic'
      expect(last_response.body).to eql 'always there:false'
      get '/admin/secret'
      expect(last_response.body).to eql 'always there:only in admin'
    end

    it 'is reopenable' do
      subject.helpers do
        def one
          1
        end
      end

      subject.helpers do
        def two
          2
        end
      end

      subject.get 'howdy' do
        [one, two]
      end

      expect { get '/howdy' }.not_to raise_error
    end

    it 'allows for modules' do
      mod = Module.new do
        def hello
          'Hello, world.'
        end
      end
      subject.helpers mod

      subject.get '/howdy' do
        hello
      end

      get '/howdy'
      expect(last_response.body).to eql 'Hello, world.'
    end

    it 'allows multiple calls with modules and blocks' do
      subject.helpers Module.new do
        def one
          1
        end
      end
      subject.helpers Module.new do
        def two
          2
        end
      end
      subject.helpers do
        def three
          3
        end
      end
      subject.get 'howdy' do
        [one, two, three]
      end
      expect { get '/howdy' }.not_to raise_error
    end
  end

  describe '.scope' do
    # TODO: refactor this to not be tied to versioning. How about a generic
    # .setting macro?
    it 'scopes the various settings' do
      subject.prefix 'new'

      subject.scope :legacy do
        prefix 'legacy'
        get '/abc' do
          'abc'
        end
      end

      subject.get '/def' do
        'def'
      end

      get '/new/abc'
      expect(last_response.status).to be 404
      get '/legacy/abc'
      expect(last_response.status).to be 200
      get '/legacy/def'
      expect(last_response.status).to be 404
      get '/new/def'
      expect(last_response.status).to be 200
    end
  end

  describe 'lifecycle' do
    let!(:lifecycle) { [] }
    let!(:standard_cycle) do
      %i[before before_validation after_validation api_call after finally]
    end

    let!(:validation_error) do
      %i[before before_validation finally]
    end

    let!(:errored_cycle) do
      %i[before before_validation after_validation api_call finally]
    end

    before do
      current_cycle = lifecycle

      subject.before do
        current_cycle << :before
      end

      subject.before_validation do
        current_cycle << :before_validation
      end

      subject.after_validation do
        current_cycle << :after_validation
      end

      subject.after do
        current_cycle << :after
      end

      subject.finally do
        current_cycle << :finally
      end
    end

    context 'when the api_call succeeds' do
      before do
        current_cycle = lifecycle

        subject.get 'api_call' do
          current_cycle << :api_call
        end
      end

      it 'follows the standard life_cycle' do
        get '/api_call'
        expect(lifecycle).to eq standard_cycle
      end
    end

    context 'when the api_call has a controlled error' do
      before do
        current_cycle = lifecycle

        subject.get 'api_call' do
          current_cycle << :api_call
          error!(:some_error)
        end
      end

      it 'follows the errored life_cycle (skips after)' do
        get '/api_call'
        expect(lifecycle).to eq errored_cycle
      end
    end

    context 'when the api_call has an exception' do
      before do
        current_cycle = lifecycle

        subject.get 'api_call' do
          current_cycle << :api_call
          raise StandardError
        end
      end

      it 'follows the errored life_cycle (skips after)' do
        expect { get '/api_call' }.to raise_error(StandardError)
        expect(lifecycle).to eq errored_cycle
      end
    end

    context 'when the api_call fails validation' do
      before do
        current_cycle = lifecycle

        subject.params do
          requires :some_param, type: String
        end

        subject.get 'api_call' do
          current_cycle << :api_call
        end
      end

      it 'follows the failed_validation cycle (skips after_validation, api_call & after)' do
        get '/api_call'
        expect(lifecycle).to eq validation_error
      end
    end
  end

  describe '.finally' do
    let!(:code) { { has_executed: false } }
    let(:block_to_run) do
      code_to_execute = code
      proc do
        code_to_execute[:has_executed] = true
      end
    end

    context 'when the ensure block has no exceptions' do
      before { subject.finally(&block_to_run) }

      context 'when no API call is made' do
        it 'has not executed the ensure code' do
          expect(code[:has_executed]).to be false
        end
      end

      context 'when no errors occurs' do
        before do
          subject.get '/no_exceptions' do
            'success'
          end
        end

        it 'executes the ensure code' do
          get '/no_exceptions'
          expect(last_response.body).to eq 'success'
          expect(code[:has_executed]).to be true
        end

        context 'with a helper' do
          let(:block_to_run) do
            code_to_execute = code
            proc do
              code_to_execute[:value] = some_helper
            end
          end

          before do
            subject.helpers do
              def some_helper
                'some_value'
              end
            end

            subject.get '/with_helpers' do
              'success'
            end
          end

          it 'has access to the helper' do
            get '/with_helpers'
            expect(code[:value]).to eq 'some_value'
          end
        end
      end

      context 'when an unhandled occurs inside the API call' do
        before do
          subject.get '/unhandled_exception' do
            raise StandardError
          end
        end

        it 'executes the ensure code' do
          expect { get '/unhandled_exception' }.to raise_error StandardError
          expect(code[:has_executed]).to be true
        end
      end

      context 'when a handled error occurs inside the API call' do
        before do
          subject.rescue_from(StandardError) { error! 'handled' }
          subject.get '/handled_exception' do
            raise StandardError
          end
        end

        it 'executes the ensure code' do
          get '/handled_exception'
          expect(code[:has_executed]).to be true
          expect(last_response.body).to eq 'handled'
        end
      end
    end
  end

  describe '.rescue_from' do
    it 'does not rescue errors when rescue_from is not set' do
      subject.get '/exception' do
        raise 'rain!'
      end
      expect { get '/exception' }.to raise_error(RuntimeError, 'rain!')
    end

    it 'uses custom helpers defined by using #helpers method' do
      subject.helpers do
        def custom_error!(name)
          error! "hello #{name}"
        end
      end
      subject.rescue_from(ArgumentError) { custom_error! :bob }
      subject.get '/custom_error' do
        raise ArgumentError
      end
      get '/custom_error'
      expect(last_response.body).to eq 'hello bob'
    end

    context 'with multiple apis' do
      let(:a) { Class.new(described_class) }
      let(:b) { Class.new(described_class) }

      before do
        a.helpers do
          def foo
            error!('foo', 401)
          end
        end
        a.rescue_from(:all) { foo }
        a.get { raise 'boo' }
        b.helpers do
          def foo
            error!('bar', 401)
          end
        end
        b.rescue_from(:all) { foo }
        b.get { raise 'boo' }
      end

      it 'avoids polluting global namespace' do
        env = Rack::MockRequest.env_for('/')

        expect(read_chunks(a.call(env)[2])).to eq(['foo'])
        expect(read_chunks(b.call(env)[2])).to eq(['bar'])
        expect(read_chunks(a.call(env)[2])).to eq(['foo'])
      end
    end

    it 'rescues all errors if rescue_from :all is called' do
      subject.rescue_from :all
      subject.get '/exception' do
        raise 'rain!'
      end
      get '/exception'
      expect(last_response.status).to be 500
      expect(last_response.body).to eq 'rain!'
    end

    it 'rescues all errors with a json formatter' do
      subject.format :json
      subject.default_format :json
      subject.rescue_from :all
      subject.get '/exception' do
        raise 'rain!'
      end
      get '/exception'
      expect(last_response.status).to be 500
      expect(last_response.body).to eq({ error: 'rain!' }.to_json)
    end

    it 'rescues only certain errors if rescue_from is called with specific errors' do
      subject.rescue_from ArgumentError
      subject.get('/rescued') { raise ArgumentError }
      subject.get('/unrescued') { raise 'beefcake' }

      get '/rescued'
      expect(last_response.status).to be 500

      expect { get '/unrescued' }.to raise_error(RuntimeError, 'beefcake')
    end

    it 'mimics default ruby "rescue" handler' do
      # The exception is matched to the rescue starting at the top, and matches only once

      subject.rescue_from ArgumentError do |e|
        error!(e, 402)
      end
      subject.rescue_from StandardError do |e|
        error!(e, 401)
      end

      subject.get('/child_of_standard_error') { raise ArgumentError }
      subject.get('/standard_error') { raise StandardError }

      get '/child_of_standard_error'
      expect(last_response.status).to be 402

      get '/standard_error'
      expect(last_response.status).to be 401
    end

    context 'CustomError subclass of Grape::Exceptions::Base' do
      before do
        module ApiSpec
          class CustomError < Grape::Exceptions::Base; end
        end
      end

      it 'does not re-raise exceptions of type Grape::Exceptions::Base' do
        subject.get('/custom_exception') { raise ApiSpec::CustomError }

        expect { get '/custom_exception' }.not_to raise_error
      end

      it 'rescues custom grape exceptions' do
        subject.rescue_from ApiSpec::CustomError do |e|
          rack_response('New Error', e.status)
        end
        subject.get '/custom_error' do
          raise ApiSpec::CustomError.new(status: 400, message: 'Custom Error')
        end

        get '/custom_error'
        expect(last_response.status).to eq(400)
        expect(last_response.body).to eq('New Error')
      end
    end

    it 'can rescue exceptions raised in the formatter' do
      formatter = double(:formatter)
      allow(formatter).to receive(:call) { raise StandardError }
      allow(Grape::Formatter).to receive(:formatter_for) { formatter }

      subject.rescue_from :all do |_e|
        rack_response('Formatter Error', 500)
      end
      subject.get('/formatter_exception') { 'Hello world' }

      get '/formatter_exception'
      expect(last_response.status).to be 500
      expect(last_response.body).to eq('Formatter Error')
    end

    it 'uses default_rescue_handler to handle invalid response from rescue_from' do
      subject.rescue_from(:all) { 'error' }
      subject.get('/') { raise }

      expect_any_instance_of(Grape::Middleware::Error).to receive(:default_rescue_handler).and_call_original
      get '/'
      expect(last_response.status).to be 500
      expect(last_response.body).to eql 'Invalid response'
    end
  end

  describe '.rescue_from klass, block' do
    it 'rescues Exception' do
      subject.rescue_from RuntimeError do |e|
        rack_response("rescued from #{e.message}", 202)
      end
      subject.get '/exception' do
        raise 'rain!'
      end
      get '/exception'
      expect(last_response.status).to be 202
      expect(last_response.body).to eq('rescued from rain!')
    end

    context 'custom errors' do
      before do
        class ConnectionError < RuntimeError; end

        class DatabaseError < RuntimeError; end

        class CommunicationError < StandardError; end
      end

      it 'rescues an error via rescue_from :all' do
        subject.rescue_from :all do |e|
          rack_response("rescued from #{e.class.name}", 500)
        end
        subject.get '/exception' do
          raise ConnectionError
        end
        get '/exception'
        expect(last_response.status).to be 500
        expect(last_response.body).to eq('rescued from ConnectionError')
      end

      it 'rescues a specific error' do
        subject.rescue_from ConnectionError do |e|
          rack_response("rescued from #{e.class.name}", 500)
        end
        subject.get '/exception' do
          raise ConnectionError
        end
        get '/exception'
        expect(last_response.status).to be 500
        expect(last_response.body).to eq('rescued from ConnectionError')
      end

      it 'rescues a subclass of an error by default' do
        subject.rescue_from RuntimeError do |e|
          rack_response("rescued from #{e.class.name}", 500)
        end
        subject.get '/exception' do
          raise ConnectionError
        end
        get '/exception'
        expect(last_response.status).to be 500
        expect(last_response.body).to eq('rescued from ConnectionError')
      end

      it 'rescues multiple specific errors' do
        subject.rescue_from ConnectionError do |e|
          rack_response("rescued from #{e.class.name}", 500)
        end
        subject.rescue_from DatabaseError do |e|
          rack_response("rescued from #{e.class.name}", 500)
        end
        subject.get '/connection' do
          raise ConnectionError
        end
        subject.get '/database' do
          raise DatabaseError
        end
        get '/connection'
        expect(last_response.status).to be 500
        expect(last_response.body).to eq('rescued from ConnectionError')
        get '/database'
        expect(last_response.status).to be 500
        expect(last_response.body).to eq('rescued from DatabaseError')
      end

      it 'does not rescue a different error' do
        subject.rescue_from RuntimeError do |e|
          rack_response("rescued from #{e.class.name}", 500)
        end
        subject.get '/uncaught' do
          raise CommunicationError
        end
        expect { get '/uncaught' }.to raise_error(CommunicationError)
      end
    end
  end

  describe '.rescue_from klass, lambda' do
    it 'rescues an error with the lambda' do
      subject.rescue_from ArgumentError, lambda {
        rack_response('rescued with a lambda', 400)
      }
      subject.get('/rescue_lambda') { raise ArgumentError }

      get '/rescue_lambda'
      expect(last_response.status).to eq(400)
      expect(last_response.body).to eq('rescued with a lambda')
    end

    it 'can execute the lambda with an argument' do
      subject.rescue_from ArgumentError, lambda { |e|
        rack_response(e.message, 400)
      }
      subject.get('/rescue_lambda') { raise ArgumentError, 'lambda takes an argument' }

      get '/rescue_lambda'
      expect(last_response.status).to eq(400)
      expect(last_response.body).to eq('lambda takes an argument')
    end
  end

  describe '.rescue_from klass, with: :method_name' do
    it 'rescues an error with the specified method name' do
      subject.helpers do
        def rescue_arg_error
          error!('500 ArgumentError', 500)
        end

        def rescue_no_method_error
          error!('500 NoMethodError', 500)
        end
      end
      subject.rescue_from ArgumentError, with: :rescue_arg_error
      subject.rescue_from NoMethodError, with: :rescue_no_method_error
      subject.get('/rescue_arg_error') { raise ArgumentError }
      subject.get('/rescue_no_method_error') { raise NoMethodError }

      get '/rescue_arg_error'
      expect(last_response.status).to eq(500)
      expect(last_response.body).to eq('500 ArgumentError')

      get '/rescue_no_method_error'
      expect(last_response.status).to eq(500)
      expect(last_response.body).to eq('500 NoMethodError')
    end

    it 'aborts if the specified method name does not exist' do
      subject.rescue_from :all, with: :not_exist_method
      subject.get('/rescue_method') { raise StandardError }

      expect { get '/rescue_method' }.to raise_error(NoMethodError, /^undefined method `not_exist_method'/)
    end

    it 'correctly chooses exception handler if :all handler is specified' do
      subject.helpers do
        def rescue_arg_error
          error!('500 ArgumentError', 500)
        end

        def rescue_all_errors
          error!('500 AnotherError', 500)
        end
      end

      subject.rescue_from ArgumentError, with: :rescue_arg_error
      subject.rescue_from :all, with: :rescue_all_errors
      subject.get('/argument_error') { raise ArgumentError }
      subject.get('/another_error') { raise NoMethodError }

      get '/argument_error'
      expect(last_response.status).to eq(500)
      expect(last_response.body).to eq('500 ArgumentError')

      get '/another_error'
      expect(last_response.status).to eq(500)
      expect(last_response.body).to eq('500 AnotherError')
    end
  end

  describe '.rescue_from klass, rescue_subclasses: boolean' do
    before do
      module ApiSpec
        module APIErrors
          class ParentError < StandardError; end

          class ChildError < ParentError; end
        end
      end
    end

    it 'rescues error as well as subclass errors with rescue_subclasses option set' do
      subject.rescue_from ApiSpec::APIErrors::ParentError, rescue_subclasses: true do |e|
        rack_response("rescued from #{e.class.name}", 500)
      end
      subject.get '/caught_child' do
        raise ApiSpec::APIErrors::ChildError
      end
      subject.get '/caught_parent' do
        raise ApiSpec::APIErrors::ParentError
      end
      subject.get '/uncaught_parent' do
        raise StandardError
      end

      get '/caught_child'
      expect(last_response.status).to be 500
      get '/caught_parent'
      expect(last_response.status).to be 500
      expect { get '/uncaught_parent' }.to raise_error(StandardError)
    end

    it 'sets rescue_subclasses to true by default' do
      subject.rescue_from ApiSpec::APIErrors::ParentError do |e|
        rack_response("rescued from #{e.class.name}", 500)
      end
      subject.get '/caught_child' do
        raise ApiSpec::APIErrors::ChildError
      end

      get '/caught_child'
      expect(last_response.status).to be 500
    end

    it 'does not rescue child errors if rescue_subclasses is false' do
      subject.rescue_from ApiSpec::APIErrors::ParentError, rescue_subclasses: false do |e|
        rack_response("rescued from #{e.class.name}", 500)
      end
      subject.get '/uncaught' do
        raise ApiSpec::APIErrors::ChildError
      end
      expect { get '/uncaught' }.to raise_error(ApiSpec::APIErrors::ChildError)
    end
  end

  describe '.rescue_from :grape_exceptions' do
    before do
      subject.rescue_from :grape_exceptions
    end

    let(:grape_exception) do
      Grape::Exceptions::Base.new(status: 400, message: 'Grape Error')
    end

    it 'rescues grape exceptions' do
      exception = grape_exception
      subject.get('/grape_exception') { raise exception }

      get '/grape_exception'

      expect(last_response.status).to eq(exception.status)
      expect(last_response.body).to eq(exception.message)
    end

    it 'rescues grape exceptions with a user-defined handler' do
      subject.rescue_from grape_exception.class do |_error|
        rack_response('Redefined Error', 403)
      end

      exception = grape_exception
      subject.get('/grape_exception') { raise exception }

      get '/grape_exception'

      expect(last_response.status).to eq(403)
      expect(last_response.body).to eq('Redefined Error')
    end
  end

  describe '.error_format' do
    it 'rescues all errors and return :txt' do
      subject.rescue_from :all
      subject.format :txt
      subject.get '/exception' do
        raise 'rain!'
      end
      get '/exception'
      expect(last_response.body).to eql 'rain!'
    end

    it 'rescues all errors and return :txt with backtrace' do
      subject.rescue_from :all, backtrace: true
      subject.format :txt
      subject.get '/exception' do
        raise 'rain!'
      end
      get '/exception'
      expect(last_response.body.start_with?("rain!\r\n")).to be true
    end

    it 'rescues all errors with a default formatter' do
      subject.default_format :foo
      subject.content_type :foo, 'text/foo'
      subject.rescue_from :all
      subject.get '/exception' do
        raise 'rain!'
      end
      get '/exception.foo'
      expect(last_response.body).to start_with 'rain!'
    end

    it 'defaults the error formatter to format' do
      subject.format :json
      subject.rescue_from :all
      subject.content_type :json, 'application/json'
      subject.content_type :foo, 'text/foo'
      subject.get '/exception' do
        raise 'rain!'
      end
      get '/exception.json'
      expect(last_response.body).to eq('{"error":"rain!"}')
      get '/exception.foo'
      expect(last_response.body).to eq('{"error":"rain!"}')
    end

    context 'class' do
      before do
        module ApiSpec
          class CustomErrorFormatter
            def self.call(message, _backtrace, _options, _env, _original_exception)
              "message: #{message} @backtrace"
            end
          end
        end
      end

      it 'returns a custom error format' do
        subject.rescue_from :all, backtrace: true
        subject.error_formatter :txt, ApiSpec::CustomErrorFormatter
        subject.get '/exception' do
          raise 'rain!'
        end
        get '/exception'
        expect(last_response.body).to eq('message: rain! @backtrace')
      end
    end

    describe 'with' do
      context 'class' do
        before do
          module ApiSpec
            class CustomErrorFormatter
              def self.call(message, _backtrace, _option, _env, _original_exception)
                "message: #{message} @backtrace"
              end
            end
          end
        end

        it 'returns a custom error format' do
          subject.rescue_from :all, backtrace: true
          subject.error_formatter :txt, with: ApiSpec::CustomErrorFormatter
          subject.get('/exception') { raise 'rain!' }

          get '/exception'
          expect(last_response.body).to eq('message: rain! @backtrace')
        end
      end
    end

    it 'rescues all errors and return :json' do
      subject.rescue_from :all
      subject.format :json
      subject.get '/exception' do
        raise 'rain!'
      end
      get '/exception'
      expect(last_response.body).to eql '{"error":"rain!"}'
    end

    it 'rescues all errors and return :json with backtrace' do
      subject.rescue_from :all, backtrace: true
      subject.format :json
      subject.get '/exception' do
        raise 'rain!'
      end
      get '/exception'
      json = ::Grape::Json.load(last_response.body)
      expect(json['error']).to eql 'rain!'
      expect(json['backtrace'].length).to be > 0
    end

    it 'rescues error! and return txt' do
      subject.format :txt
      subject.get '/error' do
        error!('Access Denied', 401)
      end
      get '/error'
      expect(last_response.body).to eql 'Access Denied'
    end

    context 'with json format' do
      before { subject.format :json }

      after do
        get '/error'
        expect(last_response.body).to eql('{"error":"failure"}')
      end

      it 'rescues error! called with a string and returns json' do
        subject.get('/error') { error!(:failure, 401) }
      end

      it 'rescues error! called with a symbol and returns json' do
        subject.get('/error') { error!(:failure, 401) }
      end

      it 'rescues error! called with a hash and returns json' do
        subject.get('/error') { error!({ error: :failure }, 401) }
      end
    end
  end

  describe '.content_type' do
    it 'sets additional content-type' do
      subject.content_type :xls, 'application/vnd.ms-excel'
      subject.get :excel do
        'some binary content'
      end
      get '/excel.xls'
      expect(last_response.content_type).to eq('application/vnd.ms-excel')
    end

    it 'allows to override content-type' do
      subject.get :content do
        content_type 'text/javascript'
        'var x = 1;'
      end
      get '/content'
      expect(last_response.content_type).to eq('text/javascript')
    end

    it 'removes existing content types' do
      subject.content_type :xls, 'application/vnd.ms-excel'
      subject.get :excel do
        'some binary content'
      end
      get '/excel.json'
      expect(last_response.status).to eq(406)
      if ActiveSupport::VERSION::MAJOR == 3
        expect(last_response.body).to eq('The requested format &#x27;txt&#x27; is not supported.')
      else
        expect(last_response.body).to eq('The requested format &#39;txt&#39; is not supported.')
      end
    end
  end

  describe '.formatter' do
    context 'multiple formatters' do
      before do
        subject.formatter :json, ->(object, _env) { "{\"custom_formatter\":\"#{object[:some]}\"}" }
        subject.formatter :txt, ->(object, _env) { "custom_formatter: #{object[:some]}" }
        subject.get :simple do
          { some: 'hash' }
        end
      end

      it 'sets one formatter' do
        get '/simple.json'
        expect(last_response.body).to eql '{"custom_formatter":"hash"}'
      end

      it 'sets another formatter' do
        get '/simple.txt'
        expect(last_response.body).to eql 'custom_formatter: hash'
      end
    end

    context 'custom formatter' do
      before do
        subject.content_type :json, 'application/json'
        subject.content_type :custom, 'application/custom'
        subject.formatter :custom, ->(object, _env) { "{\"custom_formatter\":\"#{object[:some]}\"}" }
        subject.get :simple do
          { some: 'hash' }
        end
      end

      it 'uses json' do
        get '/simple.json'
        expect(last_response.body).to eql '{"some":"hash"}'
      end

      it 'uses custom formatter' do
        get '/simple.custom', 'HTTP_ACCEPT' => 'application/custom'
        expect(last_response.body).to eql '{"custom_formatter":"hash"}'
      end
    end

    context 'custom formatter class' do
      module ApiSpec
        module CustomFormatter
          def self.call(object, _env)
            "{\"custom_formatter\":\"#{object[:some]}\"}"
          end
        end
      end
      before do
        subject.content_type :json, 'application/json'
        subject.content_type :custom, 'application/custom'
        subject.formatter :custom, ApiSpec::CustomFormatter
        subject.get :simple do
          { some: 'hash' }
        end
      end

      it 'uses json' do
        get '/simple.json'
        expect(last_response.body).to eql '{"some":"hash"}'
      end

      it 'uses custom formatter' do
        get '/simple.custom', 'HTTP_ACCEPT' => 'application/custom'
        expect(last_response.body).to eql '{"custom_formatter":"hash"}'
      end
    end
  end

  describe '.parser' do
    it 'parses data in format requested by content-type' do
      subject.format :json
      subject.post '/data' do
        { x: params[:x] }
      end
      post '/data', '{"x":42}', 'CONTENT_TYPE' => 'application/json'
      expect(last_response.status).to eq(201)
      expect(last_response.body).to eq('{"x":42}')
    end

    context 'lambda parser' do
      before do
        subject.content_type :txt, 'text/plain'
        subject.content_type :custom, 'text/custom'
        subject.parser :custom, ->(object, _env) { { object.to_sym => object.to_s.reverse } }
        subject.put :simple do
          params[:simple]
        end
      end

      ['text/custom', 'text/custom; charset=UTF-8'].each do |content_type|
        it "uses parser for #{content_type}" do
          put '/simple', 'simple', 'CONTENT_TYPE' => content_type
          expect(last_response.status).to eq(200)
          expect(last_response.body).to eql 'elpmis'
        end
      end
    end

    context 'custom parser class' do
      module ApiSpec
        module CustomParser
          def self.call(object, _env)
            { object.to_sym => object.to_s.reverse }
          end
        end
      end
      before do
        subject.content_type :txt, 'text/plain'
        subject.content_type :custom, 'text/custom'
        subject.parser :custom, ApiSpec::CustomParser
        subject.put :simple do
          params[:simple]
        end
      end

      it 'uses custom parser' do
        put '/simple', 'simple', 'CONTENT_TYPE' => 'text/custom'
        expect(last_response.status).to eq(200)
        expect(last_response.body).to eql 'elpmis'
      end
    end

    if Object.const_defined? :MultiXml
      context 'multi_xml' do
        it "doesn't parse yaml" do
          subject.put :yaml do
            params[:tag]
          end
          put '/yaml', '<tag type="symbol">a123</tag>', 'CONTENT_TYPE' => 'application/xml'
          expect(last_response.status).to eq(400)
          expect(last_response.body).to eql 'Disallowed type attribute: "symbol"'
        end
      end
    else
      context 'default xml parser' do
        it 'parses symbols' do
          subject.put :yaml do
            params[:tag]
          end
          put '/yaml', '<tag type="symbol">a123</tag>', 'CONTENT_TYPE' => 'application/xml'
          expect(last_response.status).to eq(200)
          expect(last_response.body).to eql '{"type"=>"symbol", "__content__"=>"a123"}'
        end
      end
    end
    context 'none parser class' do
      before do
        subject.parser :json, nil
        subject.put 'data' do
          "body: #{env['api.request.body']}"
        end
      end

      it 'does not parse data' do
        put '/data', 'not valid json', 'CONTENT_TYPE' => 'application/json'
        expect(last_response.status).to eq(200)
        expect(last_response.body).to eq('body: not valid json')
      end
    end
  end

  describe '.default_format' do
    before do
      subject.format :json
      subject.default_format :json
    end

    it 'returns data in default format' do
      subject.get '/data' do
        { x: 42 }
      end
      get '/data'
      expect(last_response.status).to eq(200)
      expect(last_response.body).to eq('{"x":42}')
    end

    it 'parses data in default format' do
      subject.post '/data' do
        { x: params[:x] }
      end
      post '/data', '{"x":42}', 'CONTENT_TYPE' => ''
      expect(last_response.status).to eq(201)
      expect(last_response.body).to eq('{"x":42}')
    end
  end

  describe '.default_error_status' do
    it 'allows setting default_error_status' do
      subject.rescue_from :all
      subject.default_error_status 200
      subject.get '/exception' do
        raise 'rain!'
      end
      get '/exception'
      expect(last_response.status).to be 200
    end

    it 'has a default error status' do
      subject.rescue_from :all
      subject.get '/exception' do
        raise 'rain!'
      end
      get '/exception'
      expect(last_response.status).to be 500
    end

    it 'uses the default error status in error!' do
      subject.rescue_from :all
      subject.default_error_status 400
      subject.get '/exception' do
        error! 'rain!'
      end
      get '/exception'
      expect(last_response.status).to be 400
    end
  end

  context 'http_codes' do
    let(:error_presenter) do
      Class.new(Grape::Entity) do
        expose :code
        expose :static

        def static
          'some static text'
        end
      end
    end

    it 'is used as presenter' do
      subject.desc 'some desc', http_codes: [
        [408, 'Unauthorized', error_presenter]
      ]

      subject.get '/exception' do
        error!({ code: 408 }, 408)
      end

      get '/exception'
      expect(last_response.status).to be 408
      expect(last_response.body).to eql({ code: 408, static: 'some static text' }.to_json)
    end

    it 'presented with' do
      error = { code: 408, with: error_presenter }.freeze
      subject.get '/exception' do
        error! error, 408
      end

      get '/exception'
      expect(last_response.status).to be 408
      expect(last_response.body).to eql({ code: 408, static: 'some static text' }.to_json)
    end
  end

  context 'routes' do
    describe 'empty api structure' do
      it 'returns an empty array of routes' do
        expect(subject.routes).to eq([])
      end
    end

    describe 'single method api structure' do
      before do
        subject.get :ping do
          'pong'
        end
      end

      it 'returns one route' do
        expect(subject.routes.size).to eq(1)
        route = subject.routes[0]
        expect(route.version).to be_nil
        expect(route.path).to eq('/ping(.:format)')
        expect(route.request_method).to eq('GET')
      end
    end

    describe 'api structure with two versions and a namespace' do
      before do
        subject.version 'v1', using: :path
        subject.get 'version' do
          api.version
        end
        # version v2
        subject.version 'v2', using: :path
        subject.prefix 'p'
        subject.namespace 'n1' do
          namespace 'n2' do
            get 'version' do
              api.version
            end
          end
        end
      end

      it 'returns the latest version set' do
        expect(subject.version).to eq('v2')
      end

      it 'returns versions' do
        expect(subject.versions).to eq(%w[v1 v2])
      end

      it 'sets route paths' do
        expect(subject.routes.size).to be >= 2
        expect(subject.routes[0].path).to eq('/:version/version(.:format)')
        expect(subject.routes[1].path).to eq('/p/:version/n1/n2/version(.:format)')
      end

      it 'sets route versions' do
        expect(subject.routes[0].version).to eq('v1')
        expect(subject.routes[1].version).to eq('v2')
      end

      it 'sets a nested namespace' do
        expect(subject.routes[1].namespace).to eq('/n1/n2')
      end

      it 'sets prefix' do
        expect(subject.routes[1].prefix).to eq('p')
      end
    end

    describe 'api structure with additional parameters' do
      before do
        subject.params do
          requires :token, desc: 'a token'
          optional :limit, desc: 'the limit'
        end
        subject.get 'split/:string' do
          params[:string].split(params[:token], (params[:limit] || 0).to_i)
        end
      end

      it 'splits a string' do
        get '/split/a,b,c.json', token: ','
        expect(last_response.body).to eq('["a","b","c"]')
      end

      it 'splits a string with limit' do
        get '/split/a,b,c.json', token: ',', limit: '2'
        expect(last_response.body).to eq('["a","b,c"]')
      end

      it 'sets params' do
        expect(subject.routes.map do |route|
          { params: route.params }
        end).to eq [
          {
            params: {
              'string' => '',
              'token' => { required: true, desc: 'a token' },
              'limit' => { required: false, desc: 'the limit' }
            }
          }
        ]
      end
    end

    describe 'api structure with multiple apis' do
      before do
        subject.params do
          requires :one, desc: 'a token'
          optional :two, desc: 'the limit'
        end
        subject.get 'one' do
        end

        subject.params do
          requires :three, desc: 'a token'
          optional :four, desc: 'the limit'
        end
        subject.get 'two' do
        end
      end

      it 'sets params' do
        expect(subject.routes.map do |route|
          { params: route.params }
        end).to eq [
          {
            params: {
              'one' => { required: true, desc: 'a token' },
              'two' => { required: false, desc: 'the limit' }
            }
          },
          {
            params: {
              'three' => { required: true, desc: 'a token' },
              'four' => { required: false, desc: 'the limit' }
            }
          }
        ]
      end
    end

    describe 'api structure with an api without params' do
      before do
        subject.params do
          requires :one, desc: 'a token'
          optional :two, desc: 'the limit'
        end
        subject.get 'one' do
        end

        subject.get 'two' do
        end
      end

      it 'sets params' do
        expect(subject.routes.map do |route|
          { params: route.params }
        end).to eq [
          {
            params: {
              'one' => { required: true, desc: 'a token' },
              'two' => { required: false, desc: 'the limit' }
            }
          },
          {
            params: {}
          }
        ]
      end
    end

    describe 'api with a custom route setting' do
      before do
        subject.route_setting :custom, key: 'value'
        subject.get 'one'
      end

      it 'exposed' do
        expect(subject.routes.count).to eq 1
        route = subject.routes.first
        expect(route.settings[:custom]).to eq(key: 'value')
      end
    end

    describe 'status' do
      it 'can be set to arbitrary Integer value' do
        subject.get '/foo' do
          status 210
        end
        get '/foo'
        expect(last_response.status).to eq 210
      end

      it 'can be set with a status code symbol' do
        subject.get '/foo' do
          status :see_other
        end
        get '/foo'
        expect(last_response.status).to eq 303
      end
    end
  end

  context 'desc' do
    it 'empty array of routes' do
      expect(subject.routes).to eq([])
    end

    it 'empty array of routes' do
      subject.desc 'grape api'
      expect(subject.routes).to eq([])
    end

    it 'describes a method' do
      subject.desc 'first method'
      subject.get :first
      expect(subject.routes.length).to eq(1)
      route = subject.routes.first
      expect(route.description).to eq('first method')
      expect(route.route_foo).to be_nil
      expect(route.params).to eq({})
      expect(route.options).to be_a_kind_of(Hash)
    end

    it 'has params which does not include format and version as named captures' do
      subject.version :v1, using: :path
      subject.get :first
      param_keys = subject.routes.first.params.keys
      expect(param_keys).not_to include('format')
      expect(param_keys).not_to include('version')
    end

    it 'describes methods separately' do
      subject.desc 'first method'
      subject.get :first
      subject.desc 'second method'
      subject.get :second
      expect(subject.routes.count).to eq(2)
      expect(subject.routes.map do |route|
        { description: route.description, params: route.params }
      end).to eq [
        { description: 'first method', params: {} },
        { description: 'second method', params: {} }
      ]
    end

    it 'resets desc' do
      subject.desc 'first method'
      subject.get :first
      subject.get :second
      expect(subject.routes.map do |route|
        { description: route.description, params: route.params }
      end).to eq [
        { description: 'first method', params: {} },
        { description: nil, params: {} }
      ]
    end

    it 'namespaces and describe arbitrary parameters' do
      subject.namespace 'ns' do
        desc 'ns second', foo: 'bar'
        get 'second'
      end
      expect(subject.routes.map do |route|
        { description: route.description, foo: route.route_foo, params: route.params }
      end).to eq [
        { description: 'ns second', foo: 'bar', params: {} }
      ]
    end

    it 'includes details' do
      subject.desc 'method', details: 'method details'
      subject.get 'method'
      expect(subject.routes.map do |route|
        { description: route.description, details: route.details, params: route.params }
      end).to eq [
        { description: 'method', details: 'method details', params: {} }
      ]
    end

    it 'describes a method with parameters' do
      subject.desc 'Reverses a string.', params: { 's' => { desc: 'string to reverse', type: 'string' } }
      subject.get 'reverse' do
        params[:s].reverse
      end
      expect(subject.routes.map do |route|
        { description: route.description, params: route.params }
      end).to eq [
        { description: 'Reverses a string.', params: { 's' => { desc: 'string to reverse', type: 'string' } } }
      ]
    end

    it 'does not inherit param descriptions in consequent namespaces' do
      subject.desc 'global description'
      subject.params do
        requires :param1
        optional :param2
      end
      subject.namespace 'ns1' do
        get { ; }
      end
      subject.params do
        optional :param2
      end
      subject.namespace 'ns2' do
        get { ; }
      end
      routes_doc = subject.routes.map do |route|
        { description: route.description, params: route.params }
      end
      expect(routes_doc).to eq [
        { description: 'global description',
          params: {
            'param1' => { required: true },
            'param2' => { required: false }
          } },
        { description: 'global description',
          params: {
            'param2' => { required: false }
          } }
      ]
    end

    it 'merges the parameters of the namespace with the parameters of the method' do
      subject.desc 'namespace'
      subject.params do
        requires :ns_param, desc: 'namespace parameter'
      end
      subject.namespace 'ns' do
        desc 'method'
        params do
          optional :method_param, desc: 'method parameter'
        end
        get 'method'
      end

      routes_doc = subject.routes.map do |route|
        { description: route.description, params: route.params }
      end
      expect(routes_doc).to eq [
        { description: 'method',
          params: {
            'ns_param' => { required: true, desc: 'namespace parameter' },
            'method_param' => { required: false, desc: 'method parameter' }
          } }
      ]
    end

    it 'merges the parameters of nested namespaces' do
      subject.desc 'ns1'
      subject.params do
        optional :ns_param, desc: 'ns param 1'
        requires :ns1_param, desc: 'ns1 param'
      end
      subject.namespace 'ns1' do
        desc 'ns2'
        params do
          requires :ns_param, desc: 'ns param 2'
          requires :ns2_param, desc: 'ns2 param'
        end
        namespace 'ns2' do
          desc 'method'
          params do
            optional :method_param, desc: 'method param'
          end
          get 'method'
        end
      end
      expect(subject.routes.map do |route|
        { description: route.description, params: route.params }
      end).to eq [
        { description: 'method',
          params: {
            'ns_param' => { required: true, desc: 'ns param 2' },
            'ns1_param' => { required: true, desc: 'ns1 param' },
            'ns2_param' => { required: true, desc: 'ns2 param' },
            'method_param' => { required: false, desc: 'method param' }
          } }
      ]
    end

    it 'groups nested params and prevents overwriting of params with same name in different groups' do
      subject.desc 'method'
      subject.params do
        group :group1, type: Array do
          optional :param1, desc: 'group1 param1 desc'
          requires :param2, desc: 'group1 param2 desc'
        end
        group :group2, type: Array do
          optional :param1, desc: 'group2 param1 desc'
          requires :param2, desc: 'group2 param2 desc'
        end
      end
      subject.get 'method'

      expect(subject.routes.map(&:params)).to eq [{
        'group1' => { required: true, type: 'Array' },
        'group1[param1]' => { required: false, desc: 'group1 param1 desc' },
        'group1[param2]' => { required: true, desc: 'group1 param2 desc' },
        'group2' => { required: true, type: 'Array' },
        'group2[param1]' => { required: false, desc: 'group2 param1 desc' },
        'group2[param2]' => { required: true, desc: 'group2 param2 desc' }
      }]
    end

    it 'uses full name of parameters in nested groups' do
      subject.desc 'nesting'
      subject.params do
        requires :root_param, desc: 'root param'
        group :nested, type: Array do
          requires :nested_param, desc: 'nested param'
        end
      end
      subject.get 'method'
      expect(subject.routes.map do |route|
        { description: route.description, params: route.params }
      end).to eq [
        { description: 'nesting',
          params: {
            'root_param' => { required: true, desc: 'root param' },
            'nested' => { required: true, type: 'Array' },
            'nested[nested_param]' => { required: true, desc: 'nested param' }
          } }
      ]
    end

    it 'allows to set the type attribute on :group element' do
      subject.params do
        group :foo, type: Array do
          optional :bar
        end
      end
    end

    it 'parses parameters when no description is given' do
      subject.params do
        requires :one_param, desc: 'one param'
      end
      subject.get 'method'
      expect(subject.routes.map do |route|
        { description: route.description, params: route.params }
      end).to eq [
        { description: nil, params: { 'one_param' => { required: true, desc: 'one param' } } }
      ]
    end

    it 'does not symbolize params' do
      subject.desc 'Reverses a string.', params: { 's' => { desc: 'string to reverse', type: 'string' } }
      subject.get 'reverse/:s' do
        params[:s].reverse
      end
      expect(subject.routes.map do |route|
        { description: route.description, params: route.params }
      end).to eq [
        { description: 'Reverses a string.', params: { 's' => { desc: 'string to reverse', type: 'string' } } }
      ]
    end
  end

  describe '.mount' do
    let(:mounted_app) { ->(_env) { [200, {}, ['MOUNTED']] } }

    context 'with a bare rack app' do
      before do
        subject.mount mounted_app => '/mounty'
      end

      it 'makes a bare Rack app available at the endpoint' do
        get '/mounty'
        expect(last_response.body).to eq('MOUNTED')
      end

      it 'anchors the routes, passing all subroutes to it' do
        get '/mounty/awesome'
        expect(last_response.body).to eq('MOUNTED')
      end

      it 'is able to cascade' do
        subject.mount lambda { |env|
          headers = {}
          headers['X-Cascade'] == 'pass' unless env['PATH_INFO'].include?('boo')
          [200, headers, ['Farfegnugen']]
        } => '/'

        get '/boo'
        expect(last_response.body).to eq('Farfegnugen')
        get '/mounty'
        expect(last_response.body).to eq('MOUNTED')
      end
    end

    context 'without a hash' do
      it 'calls through setting the route to "/"' do
        subject.mount mounted_app
        get '/'
        expect(last_response.body).to eq('MOUNTED')
      end
    end

    context 'mounting an API' do
      it 'applies the settings of the mounting api' do
        subject.version 'v1', using: :path

        subject.namespace :cool do
          app = Class.new(Grape::API) # rubocop:disable RSpec/DescribedClass
          app.get('/awesome') do
            'yo'
          end

          mount app
        end

        get '/v1/cool/awesome'
        expect(last_response.body).to eq('yo')
      end

      it 'applies the settings to nested mounted apis' do
        subject.version 'v1', using: :path

        subject.namespace :cool do
          inner_app = Class.new(Grape::API) # rubocop:disable RSpec/DescribedClass
          inner_app.get('/awesome') do
            'yo'
          end

          app = Class.new(Grape::API) # rubocop:disable RSpec/DescribedClass
          app.mount inner_app
          mount app
        end

        get '/v1/cool/awesome'
        expect(last_response.body).to eq('yo')
      end

      context 'when some rescues are defined by mounted' do
        it 'inherits parent rescues' do
          subject.rescue_from :all do |e|
            rack_response("rescued from #{e.message}", 202)
          end

          app = Class.new(described_class)

          subject.namespace :mounted do
            app.rescue_from ArgumentError
            app.get('/fail') { raise 'doh!' }
            mount app
          end

          get '/mounted/fail'
          expect(last_response.status).to be 202
          expect(last_response.body).to eq('rescued from doh!')
        end

        it 'prefers rescues defined by mounted if they rescue similar error class' do
          subject.rescue_from StandardError do
            rack_response('outer rescue')
          end

          app = Class.new(described_class)

          subject.namespace :mounted do
            rescue_from StandardError do
              rack_response('inner rescue')
            end
            app.get('/fail') { raise 'doh!' }
            mount app
          end

          get '/mounted/fail'
          expect(last_response.body).to eq('inner rescue')
        end

        it 'prefers rescues defined by mounted even if outer is more specific' do
          subject.rescue_from ArgumentError do
            rack_response('outer rescue')
          end

          app = Class.new(described_class)

          subject.namespace :mounted do
            rescue_from StandardError do
              rack_response('inner rescue')
            end
            app.get('/fail') { raise ArgumentError.new }
            mount app
          end

          get '/mounted/fail'
          expect(last_response.body).to eq('inner rescue')
        end

        it 'prefers more specific rescues defined by mounted' do
          subject.rescue_from StandardError do
            rack_response('outer rescue')
          end

          app = Class.new(described_class)

          subject.namespace :mounted do
            rescue_from ArgumentError do
              rack_response('inner rescue')
            end
            app.get('/fail') { raise ArgumentError.new }
            mount app
          end

          get '/mounted/fail'
          expect(last_response.body).to eq('inner rescue')
        end
      end

      it 'collects the routes of the mounted api' do
        subject.namespace :cool do
          app = Class.new(Grape::API) # rubocop:disable RSpec/DescribedClass
          app.get('/awesome') {}
          app.post('/sauce') {}
          mount app
        end
        expect(subject.routes.size).to eq(2)
        expect(subject.routes.first.path).to match(%r{/cool/awesome})
        expect(subject.routes.last.path).to match(%r{/cool/sauce})
      end

      it 'mounts on a path' do
        subject.namespace :cool do
          app = Class.new(Grape::API) # rubocop:disable RSpec/DescribedClass
          app.get '/awesome' do
            'sauce'
          end
          mount app => '/mounted'
        end
        get '/mounted/cool/awesome'
        expect(last_response.status).to eq(200)
        expect(last_response.body).to eq('sauce')
      end

      it 'mounts on a nested path' do
        APP1 = Class.new(described_class)
        APP2 = Class.new(described_class)
        APP2.get '/nice' do
          'play'
        end
        # NOTE: that the reverse won't work, mount from outside-in
        APP3 = subject
        APP3.mount APP1 => '/app1'
        APP1.mount APP2 => '/app2'
        get '/app1/app2/nice'
        expect(last_response.status).to eq(200)
        expect(last_response.body).to eq('play')
        options '/app1/app2/nice'
        expect(last_response.status).to eq(204)
      end

      it 'responds to options' do
        app = Class.new(described_class)
        app.get '/colour' do
          'red'
        end
        app.namespace :pears do
          get '/colour' do
            'green'
          end
        end
        subject.namespace :apples do
          mount app
        end

        get '/apples/colour'
        expect(last_response.status).to be 200
        expect(last_response.body).to eq('red')
        options '/apples/colour'
        expect(last_response.status).to be 204
        get '/apples/pears/colour'
        expect(last_response.status).to be 200
        expect(last_response.body).to eq('green')
        options '/apples/pears/colour'
        expect(last_response.status).to be 204
      end

      it 'responds to options with path versioning' do
        subject.version 'v1', using: :path
        subject.namespace :apples do
          app = Class.new(Grape::API) # rubocop:disable RSpec/DescribedClass
          app.get('/colour') do
            'red'
          end
          mount app
        end

        get '/v1/apples/colour'
        expect(last_response.status).to be 200
        expect(last_response.body).to eq('red')
        options '/v1/apples/colour'
        expect(last_response.status).to be 204
      end

      it 'mounts a versioned API with nested resources' do
        api = Class.new(described_class) do
          version 'v1'
          resources :users do
            get :hello do
              'hello users'
            end
          end
        end
        subject.mount api

        get '/v1/users/hello'
        expect(last_response.body).to eq('hello users')
      end

      it 'mounts a prefixed API with nested resources' do
        api = Class.new(described_class) do
          prefix 'api'
          resources :users do
            get :hello do
              'hello users'
            end
          end
        end
        subject.mount api

        get '/api/users/hello'
        expect(last_response.body).to eq('hello users')
      end

      it 'applies format to a mounted API with nested resources' do
        api = Class.new(described_class) do
          format :json
          resources :users do
            get do
              { users: true }
            end
          end
        end
        subject.mount api

        get '/users'
        expect(last_response.body).to eq({ users: true }.to_json)
      end

      it 'applies auth to a mounted API with nested resources' do
        api = Class.new(described_class) do
          format :json
          http_basic do |username, password|
            username == 'username' && password == 'password'
          end
          resources :users do
            get do
              { users: true }
            end
          end
        end
        subject.mount api

        get '/users'
        expect(last_response.status).to eq(401)

        get '/users', {}, 'HTTP_AUTHORIZATION' => encode_basic_auth('username', 'password')
        expect(last_response.body).to eq({ users: true }.to_json)
      end

      it 'mounts multiple versioned APIs with nested resources' do
        api1 = Class.new(described_class) do
          version 'one', using: :header, vendor: 'test'
          resources :users do
            get :hello do
              'one'
            end
          end
        end

        api2 = Class.new(described_class) do
          version 'two', using: :header, vendor: 'test'
          resources :users do
            get :hello do
              'two'
            end
          end
        end

        subject.mount api1
        subject.mount api2

        versioned_get '/users/hello', 'one', using: :header, vendor: 'test'
        expect(last_response.body).to eq('one')
        versioned_get '/users/hello', 'two', using: :header, vendor: 'test'
        expect(last_response.body).to eq('two')
      end

      it 'recognizes potential versions with mounted path' do
        a = Class.new(described_class) do
          version :v1, using: :path

          get '/hello' do
            'hello'
          end
        end

        b = Class.new(described_class) do
          version :v1, using: :path

          get '/world' do
            'world'
          end
        end

        subject.mount a => '/one'
        subject.mount b => '/two'

        get '/one/v1/hello'
        expect(last_response.status).to eq 200

        get '/two/v1/world'
        expect(last_response.status).to eq 200
      end

      context 'when mounting class extends a subclass of Grape::API' do
        it 'mounts APIs with the same superclass' do
          base_api = Class.new(described_class)
          a = Class.new(base_api)
          b = Class.new(base_api)

          expect { a.mount b }.not_to raise_error
        end
      end

      context 'when including a module' do
        let(:included_module) do
          Module.new do
            def self.included(base)
              base.extend(ClassMethods)
            end

            module ClassMethods
              def my_method
                @test = true
              end
            end
          end
        end

        it 'correctlies include module in nested mount' do
          module_to_include = included_module
          v1 = Class.new(described_class) do
            version :v1, using: :path
            include module_to_include
            my_method
          end
          v2 = Class.new(described_class) do
            version :v2, using: :path
          end
          segment_base = Class.new(described_class) do
            mount v1
            mount v2
          end

          Class.new(described_class) do
            mount segment_base
          end

          expect(v1.my_method).to be_truthy
        end
      end
    end
  end

  describe '.endpoints' do
    it 'adds one for each route created' do
      subject.get '/'
      subject.post '/'
      expect(subject.endpoints.size).to eq(2)
    end
  end

  describe '.compile' do
    it 'sets the instance' do
      expect(subject.instance).to be_nil
      subject.compile
      expect(subject.instance).to be_kind_of(subject.base_instance)
    end
  end

  describe '.change!' do
    it 'invalidates any compiled instance' do
      subject.compile
      subject.change!
      expect(subject.instance).to be_nil
    end
  end

  describe '.endpoint' do
    before do
      subject.format :json
      subject.get '/endpoint/options' do
        {
          path: options[:path],
          source_location: source.source_location
        }
      end
    end

    it 'path' do
      get '/endpoint/options'
      options = ::Grape::Json.load(last_response.body)
      expect(options['path']).to eq(['/endpoint/options'])
      expect(options['source_location'][0]).to include 'api_spec.rb'
      expect(options['source_location'][1].to_i).to be > 0
    end
  end

  describe '.route' do
    context 'plain' do
      before do
        subject.get '/' do
          route.path
        end
        subject.get '/path' do
          route.path
        end
      end

      it 'provides access to route info' do
        get '/'
        expect(last_response.body).to eq('/(.:format)')
        get '/path'
        expect(last_response.body).to eq('/path(.:format)')
      end
    end

    context 'with desc' do
      before do
        subject.desc 'returns description'
        subject.get '/description' do
          route.description
        end
        subject.desc 'returns parameters', params: { 'x' => 'y' }
        subject.get '/params/:id' do
          route.params[params[:id]]
        end
      end

      it 'returns route description' do
        get '/description'
        expect(last_response.body).to eq('returns description')
      end

      it 'returns route parameters' do
        get '/params/x'
        expect(last_response.body).to eq('y')
      end
    end
  end

  describe '.format' do
    context ':txt' do
      before do
        subject.format :txt
        subject.content_type :json, 'application/json'
        subject.get '/meaning_of_life' do
          { meaning_of_life: 42 }
        end
      end

      it 'forces txt without an extension' do
        get '/meaning_of_life'
        expect(last_response.body).to eq({ meaning_of_life: 42 }.to_s)
      end

      it 'does not force txt with an extension' do
        get '/meaning_of_life.json'
        expect(last_response.body).to eq({ meaning_of_life: 42 }.to_json)
      end

      it 'forces txt from a non-accepting header' do
        get '/meaning_of_life', {}, 'HTTP_ACCEPT' => 'application/json'
        expect(last_response.body).to eq({ meaning_of_life: 42 }.to_s)
      end
    end

    context ':txt only' do
      before do
        subject.format :txt
        subject.get '/meaning_of_life' do
          { meaning_of_life: 42 }
        end
      end

      it 'forces txt without an extension' do
        get '/meaning_of_life'
        expect(last_response.body).to eq({ meaning_of_life: 42 }.to_s)
      end

      it 'accepts specified extension' do
        get '/meaning_of_life.txt'
        expect(last_response.body).to eq({ meaning_of_life: 42 }.to_s)
      end

      it 'does not accept extensions other than specified' do
        get '/meaning_of_life.json'
        expect(last_response.status).to eq(404)
      end

      it 'forces txt from a non-accepting header' do
        get '/meaning_of_life', {}, 'HTTP_ACCEPT' => 'application/json'
        expect(last_response.body).to eq({ meaning_of_life: 42 }.to_s)
      end
    end

    context ':json' do
      before do
        subject.format :json
        subject.content_type :txt, 'text/plain'
        subject.get '/meaning_of_life' do
          { meaning_of_life: 42 }
        end
      end

      it 'forces json without an extension' do
        get '/meaning_of_life'
        expect(last_response.body).to eq({ meaning_of_life: 42 }.to_json)
      end

      it 'does not force json with an extension' do
        get '/meaning_of_life.txt'
        expect(last_response.body).to eq({ meaning_of_life: 42 }.to_s)
      end

      it 'forces json from a non-accepting header' do
        get '/meaning_of_life', {}, 'HTTP_ACCEPT' => 'text/html'
        expect(last_response.body).to eq({ meaning_of_life: 42 }.to_json)
      end

      it 'can be overwritten with an explicit content type' do
        subject.get '/meaning_of_life_with_content_type' do
          content_type 'text/plain'
          { meaning_of_life: 42 }.to_s
        end
        get '/meaning_of_life_with_content_type'
        expect(last_response.body).to eq({ meaning_of_life: 42 }.to_s)
      end

      it 'raised :error from middleware' do
        middleware = Class.new(Grape::Middleware::Base) do
          def before
            throw :error, message: 'Unauthorized', status: 42
          end
        end
        subject.use middleware
        subject.get do
        end
        get '/'
        expect(last_response.status).to eq(42)
        expect(last_response.body).to eq({ error: 'Unauthorized' }.to_json)
      end
    end

    context ':serializable_hash' do
      class SerializableHashExample
        def serializable_hash
          { abc: 'def' }
        end
      end

      before do
        subject.format :serializable_hash
      end

      it 'instance' do
        subject.get '/example' do
          SerializableHashExample.new
        end
        get '/example'
        expect(last_response.body).to eq('{"abc":"def"}')
      end

      it 'root' do
        subject.get '/example' do
          { 'root' => SerializableHashExample.new }
        end
        get '/example'
        expect(last_response.body).to eq('{"root":{"abc":"def"}}')
      end

      it 'array' do
        subject.get '/examples' do
          [SerializableHashExample.new, SerializableHashExample.new]
        end
        get '/examples'
        expect(last_response.body).to eq('[{"abc":"def"},{"abc":"def"}]')
      end
    end

    context ':xml' do
      before do
        subject.format :xml
      end

      it 'string' do
        subject.get '/example' do
          'example'
        end
        get '/example'
        expect(last_response.status).to eq(500)
        expect(last_response.body).to eq <<~XML
          <?xml version="1.0" encoding="UTF-8"?>
          <error>
            <message>cannot convert String to xml</message>
          </error>
        XML
      end

      it 'hash' do
        subject.get '/example' do
          {
            example1: 'example1',
            example2: 'example2'
          }
        end
        get '/example'
        expect(last_response.status).to eq(200)
        expect(last_response.body).to eq <<~XML
          <?xml version="1.0" encoding="UTF-8"?>
          <hash>
            <example1>example1</example1>
            <example2>example2</example2>
          </hash>
        XML
      end

      it 'array' do
        subject.get '/example' do
          %w[example1 example2]
        end
        get '/example'
        expect(last_response.status).to eq(200)
        expect(last_response.body).to eq <<~XML
          <?xml version="1.0" encoding="UTF-8"?>
          <strings type="array">
            <string>example1</string>
            <string>example2</string>
          </strings>
        XML
      end

      it 'raised :error from middleware' do
        middleware = Class.new(Grape::Middleware::Base) do
          def before
            throw :error, message: 'Unauthorized', status: 42
          end
        end
        subject.use middleware
        subject.get do
        end
        get '/'
        expect(last_response.status).to eq(42)
        expect(last_response.body).to eq <<~XML
          <?xml version="1.0" encoding="UTF-8"?>
          <error>
            <message>Unauthorized</message>
          </error>
        XML
      end
    end
  end

  describe '.configure' do
    context 'when given a block' do
      it 'returns self' do
        expect(subject.configure {}).to be subject
      end

      it 'calls the block passing the config' do
        call = [false, nil]
        subject.configure do |config|
          call = [true, config]
        end

        expect(call[0]).to be true
        expect(call[1]).not_to be_nil
      end
    end

    context 'when not given a block' do
      it 'returns a configuration object' do
        expect(subject.configure).to respond_to(:[], :[]=)
      end
    end

    it 'allows configuring the api' do
      subject.configure do |config|
        config[:hello] = 'hello'
        config[:bread] = 'bread'
      end

      subject.get '/hello-bread' do
        "#{configuration[:hello]} #{configuration[:bread]}"
      end

      get '/hello-bread'
      expect(last_response.body).to eq 'hello bread'
    end
  end

  context 'catch-all' do
    before do
      api1 = Class.new(described_class)
      api1.version 'v1', using: :path
      api1.get 'hello' do
        'v1'
      end
      api2 = Class.new(described_class)
      api2.version 'v2', using: :path
      api2.get 'hello' do
        'v2'
      end
      subject.mount api1
      subject.mount api2
    end

    [true, false].each do |anchor|
      it "anchor=#{anchor}" do
        subject.route :any, '*path', anchor: anchor do
          error!("Unrecognized request path: #{params[:path]} - #{env['PATH_INFO']}#{env['SCRIPT_NAME']}", 404)
        end
        get '/v1/hello'
        expect(last_response.status).to eq(200)
        expect(last_response.body).to eq('v1')
        get '/v2/hello'
        expect(last_response.status).to eq(200)
        expect(last_response.body).to eq('v2')
        options '/v2/hello'
        expect(last_response.status).to eq(204)
        expect(last_response.body).to be_blank
        head '/v2/hello'
        expect(last_response.status).to eq(200)
        expect(last_response.body).to be_blank
        get '/foobar'
        expect(last_response.status).to eq(404)
        expect(last_response.body).to eq('Unrecognized request path: foobar - /foobar')
      end
    end
  end

  context 'cascading' do
    context 'via version' do
      it 'cascades' do
        subject.version 'v1', using: :path, cascade: true
        get '/v1/hello'
        expect(last_response.status).to eq(404)
        expect(last_response.headers['X-Cascade']).to eq('pass')
      end

      it 'does not cascade' do
        subject.version 'v2', using: :path, cascade: false
        get '/v2/hello'
        expect(last_response.status).to eq(404)
        expect(last_response.headers.keys).not_to include 'X-Cascade'
      end
    end

    context 'via endpoint' do
      it 'cascades' do
        subject.cascade true
        get '/hello'
        expect(last_response.status).to eq(404)
        expect(last_response.headers['X-Cascade']).to eq('pass')
      end

      it 'does not cascade' do
        subject.cascade false
        get '/hello'
        expect(last_response.status).to eq(404)
        expect(last_response.headers.keys).not_to include 'X-Cascade'
      end
    end
  end

  context 'with json default_error_formatter' do
    it 'returns json error' do
      subject.content_type :json, 'application/json'
      subject.default_error_formatter :json
      subject.get '/something' do
        'foo'
      end
      get '/something'
      expect(last_response.status).to eq(406)
      if ActiveSupport::VERSION::MAJOR == 3
        expect(last_response.body).to eq('{&quot;error&quot;:&quot;The requested format &#x27;txt&#x27; is not supported.&quot;}')
      else
        expect(last_response.body).to eq('{&quot;error&quot;:&quot;The requested format &#39;txt&#39; is not supported.&quot;}')
      end
    end
  end

  context 'with unsafe HTML format specified' do
    it 'escapes the HTML' do
      subject.content_type :json, 'application/json'
      subject.get '/something' do
        'foo'
      end
      get '/something?format=<script>blah</script>'
      expect(last_response.status).to eq(406)
      if ActiveSupport::VERSION::MAJOR == 3
        expect(last_response.body).to eq('The requested format &#x27;&lt;script&gt;blah&lt;/script&gt;&#x27; is not supported.')
      else
        expect(last_response.body).to eq('The requested format &#39;&lt;script&gt;blah&lt;/script&gt;&#39; is not supported.')
      end
    end
  end

  context 'body' do
    context 'false' do
      before do
        subject.get '/blank' do
          body false
        end
      end

      it 'returns blank body' do
        get '/blank'
        expect(last_response.status).to eq(204)
        expect(last_response.body).to be_blank
      end
    end

    context 'plain text' do
      before do
        subject.get '/text' do
          content_type 'text/plain'
          body 'Hello World'
          'ignored'
        end
      end

      it 'returns blank body' do
        get '/text'
        expect(last_response.status).to eq(200)
        expect(last_response.body).to eq 'Hello World'
      end
    end
  end

  describe 'normal class methods' do
    subject(:grape_api) { Class.new(described_class) }

    before do
      stub_const('MyAPI', grape_api)
    end

    it 'can find the appropiate name' do
      expect(grape_api.name).to eq 'MyAPI'
    end

    it 'is equal to itself' do
      expect(grape_api.itself).to eq grape_api
      expect(grape_api).to eq MyAPI
      expect(grape_api.eql?(MyAPI))
    end
  end

  describe '.inherited' do
    context 'overriding within class' do
      let(:root_api) do
        Class.new(described_class) do
          @bar = 'Hello, world'

          def self.inherited(child_api)
            super
            child_api.instance_variable_set(:@foo, @bar.dup)
          end
        end
      end

      let(:child_api) { Class.new(root_api) }

      it 'allows overriding the hook' do
        expect(child_api.instance_variable_get(:@foo)).to eq('Hello, world')
      end
    end

    context 'overriding via composition' do
      module Inherited
        def inherited(api)
          super
          api.instance_variable_set(:@foo, @bar.dup)
        end
      end

      let(:root_api) do
        Class.new(described_class) do
          @bar = 'Hello, world'
          extend Inherited
        end
      end

      let(:child_api) { Class.new(root_api) }

      it 'allows overriding the hook' do
        expect(child_api.instance_variable_get(:@foo)).to eq('Hello, world')
      end
    end
  end

  describe 'const_missing' do
    subject(:grape_api) { Class.new(described_class) }

    let(:mounted) do
      Class.new(described_class) do
        get '/missing' do
          SomeRandomConstant
        end
      end
    end

    before { subject.mount mounted => '/const' }

    it 'raises an error' do
      expect { get '/const/missing' }.to raise_error(NameError).with_message(/SomeRandomConstant/)
    end
  end

  describe 'custom route helpers on nested APIs' do
    subject(:grape_api) do
      Class.new(described_class) do
        version 'v1', using: :path
      end
    end

    let(:shared_api_module) do
      Module.new do
        # rubocop:disable Style/ExplicitBlockArgument because this causes
        #   the underlying issue in this form
        def uniqe_id_route
          params do
            use :unique_id
          end
          route_param(:id) do
            yield
          end
        end
        # rubocop:enable Style/ExplicitBlockArgument
      end
    end
    let(:shared_api_definitions) do
      Module.new do
        extend ActiveSupport::Concern

        included do
          helpers do
            params :unique_id do
              requires :id, type: String,
                            allow_blank: false,
                            regexp: /\d+-\d+/
            end
          end
        end
      end
    end
    let(:orders_root) do
      shared = shared_api_definitions
      find = orders_find_endpoint
      Class.new(described_class) do
        include shared

        namespace(:orders) do
          mount find
        end
      end
    end
    let(:orders_find_endpoint) do
      shared = shared_api_definitions
      Class.new(described_class) do
        include shared

        uniqe_id_route do
          desc 'Fetch a single order' do
            detail 'While specifying the order id on the route'
          end
          get { params[:id] }
        end
      end
    end

    before do
      Grape::API::Instance.extend(shared_api_module)
      subject.mount orders_root
    end

    it 'returns an error when the id is bad' do
      get '/v1/orders/abc'
      expect(last_response.body).to be_eql('id is invalid')
    end

    it 'returns the given id when it is valid' do
      get '/v1/orders/1-2'
      expect(last_response.body).to be_eql('1-2')
    end
  end
end