forked from jsonapi-rb/jsonapi-rails
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrender_jsonapi_spec.rb
89 lines (70 loc) · 2.26 KB
/
render_jsonapi_spec.rb
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
require 'rails_helper'
describe ActionController::Base, '#render', type: :controller do
context 'when calling render jsonapi:' do
controller do
def index
render jsonapi: nil
end
end
subject { JSON.parse(response.body) }
it 'renders a JSON API success document' do
get :index
expect(response.content_type).to eq('application/vnd.api+json')
expect(subject.key?('data')).to be true
end
end
context 'when using a cache' do
controller do
def serializer
Class.new(JSONAPI::Serializable::Resource) do
type 'users'
attributes :id, :name, :dob
def jsonapi_cache_key(*)
'cache_key'
end
end
end
def user
OpenStruct.new(id: 1, name: 'Johnny Cache', dob: Time.new(2021,1,1))
end
def index
render jsonapi: [user],
class: { OpenStruct: serializer }
end
def index_with_caching
render jsonapi: [user],
class: { OpenStruct: serializer },
cache: Rails.cache
end
end
before do
routes.draw do
get "index_with_caching" => "anonymous#index_with_caching"
get "index" => "anonymous#index"
end
end
let(:rendered_json) { JSON.parse(response.body) }
it 'renders a JSON API success document' do
get :index_with_caching
expect(response.content_type).to eq('application/vnd.api+json')
expect(rendered_json.key?('data')).to be true
end
it 'caches resources' do
get :index_with_caching
expect(Rails.cache.exist?('cache_key')).to be true
expect(JSON.parse(Rails.cache.read('cache_key'))).to eq rendered_json['data'].first
end
it 'renders equivalent JSON whether caching or not' do
expected_response = {
"data"=>[{"id"=>"1", "type"=>"users", "attributes"=>{"id"=>1, "name"=>"Johnny Cache", "dob"=>"2021-01-01T00:00:00.000+00:00"}}],
"jsonapi"=>{"version"=>"1.0"}
}
get :index
response_with_no_caching = rendered_json.deep_dup
get :index_with_caching
response_with_caching = rendered_json
expect(response_with_no_caching).to eq expected_response
expect(response_with_caching).to eq expected_response
end
end
end