@@ -23,32 +23,67 @@ def index
23
23
def serializer
24
24
Class . new ( JSONAPI ::Serializable ::Resource ) do
25
25
type 'users'
26
- attribute : name
26
+ attributes :id , : name, :dob
27
27
28
28
def jsonapi_cache_key ( *)
29
- 'foo '
29
+ 'cache_key '
30
30
end
31
31
end
32
32
end
33
33
34
+ def user
35
+ OpenStruct . new ( id : 1 , name : 'Johnny Cache' , dob : Time . new ( 2021 , 1 , 1 ) )
36
+ end
37
+
34
38
def index
35
- user = OpenStruct . new ( id : 1 , name : 'Lucas' )
39
+ render jsonapi : [ user ] ,
40
+ class : { OpenStruct : serializer }
41
+ end
36
42
37
- render jsonapi : user ,
43
+ def index_with_caching
44
+ render jsonapi : [ user ] ,
38
45
class : { OpenStruct : serializer } ,
39
46
cache : Rails . cache
40
47
end
41
48
end
42
49
43
- subject { JSON . parse ( response . body ) }
50
+ before do
51
+ routes . draw do
52
+ get "index_with_caching" => "anonymous#index_with_caching"
53
+ get "index" => "anonymous#index"
54
+ end
55
+ end
56
+
57
+ let ( :rendered_json ) { JSON . parse ( response . body ) }
44
58
45
59
it 'renders a JSON API success document' do
46
- get :index
47
- expect ( Rails . cache . exist? ( 'foo' ) ) . to be true
48
- get :index
60
+ get :index_with_caching
49
61
50
62
expect ( response . content_type ) . to eq ( 'application/vnd.api+json' )
51
- expect ( subject . key? ( 'data' ) ) . to be true
63
+ expect ( rendered_json . key? ( 'data' ) ) . to be true
64
+ end
65
+
66
+ it 'caches resources' do
67
+ get :index_with_caching
68
+
69
+ expect ( Rails . cache . exist? ( 'cache_key' ) ) . to be true
70
+ expect ( JSON . parse ( Rails . cache . read ( 'cache_key' ) ) ) . to eq rendered_json [ 'data' ] . first
71
+ end
72
+
73
+ it 'renders equivalent JSON whether caching or not' do
74
+ expected_response = {
75
+ "data" => [ { "id" => "1" , "type" => "users" , "attributes" => { "id" => 1 , "name" => "Johnny Cache" , "dob" => "2021-01-01T00:00:00.000+00:00" } } ] ,
76
+ "jsonapi" => { "version" => "1.0" }
77
+ }
78
+
79
+ get :index
80
+ response_with_no_caching = rendered_json . deep_dup
81
+
82
+ get :index_with_caching
83
+ response_with_caching = rendered_json
84
+
85
+ expect ( response_with_no_caching ) . to eq expected_response
86
+ expect ( response_with_caching ) . to eq expected_response
52
87
end
53
88
end
54
89
end
0 commit comments