@@ -23,32 +23,67 @@ def index
2323 def serializer
2424 Class . new ( JSONAPI ::Serializable ::Resource ) do
2525 type 'users'
26- attribute : name
26+ attributes :id , : name, :dob
2727
2828 def jsonapi_cache_key ( *)
29- 'foo '
29+ 'cache_key '
3030 end
3131 end
3232 end
3333
34+ def user
35+ OpenStruct . new ( id : 1 , name : 'Johnny Cache' , dob : Time . new ( 2021 , 1 , 1 ) )
36+ end
37+
3438 def index
35- user = OpenStruct . new ( id : 1 , name : 'Lucas' )
39+ render jsonapi : [ user ] ,
40+ class : { OpenStruct : serializer }
41+ end
3642
37- render jsonapi : user ,
43+ def index_with_caching
44+ render jsonapi : [ user ] ,
3845 class : { OpenStruct : serializer } ,
3946 cache : Rails . cache
4047 end
4148 end
4249
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 ) }
4458
4559 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
4961
5062 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
5287 end
5388 end
5489end
0 commit comments