|
| 1 | +require 'spec_helper' |
| 2 | + |
| 3 | +class Cache |
| 4 | + def initialize |
| 5 | + @cache = {} |
| 6 | + end |
| 7 | + |
| 8 | + def fetch_multi(keys) |
| 9 | + keys.each_with_object({}) do |k, h| |
| 10 | + @cache[k] = yield(k) unless @cache.key?(k) |
| 11 | + h[k] = @cache[k] |
| 12 | + end |
| 13 | + end |
| 14 | +end |
| 15 | + |
| 16 | +describe JSONAPI::Renderer, '#render' do |
| 17 | + before(:all) do |
| 18 | + @users = [ |
| 19 | + UserResource.new(1, 'User 1', '123 Example st.', []), |
| 20 | + UserResource.new(2, 'User 2', '234 Example st.', []), |
| 21 | + UserResource.new(3, 'User 3', '345 Example st.', []), |
| 22 | + UserResource.new(4, 'User 4', '456 Example st.', []) |
| 23 | + ] |
| 24 | + @posts = [ |
| 25 | + PostResource.new(1, 'Post 1', 'yesterday', @users[1]), |
| 26 | + PostResource.new(2, 'Post 2', 'today', @users[0]), |
| 27 | + PostResource.new(3, 'Post 3', 'tomorrow', @users[1]) |
| 28 | + ] |
| 29 | + @users[0].posts = [@posts[1]] |
| 30 | + @users[1].posts = [@posts[0], @posts[2]] |
| 31 | + end |
| 32 | + |
| 33 | + it 'renders included relationships' do |
| 34 | + cache = Cache.new |
| 35 | + # Warm up the cache. |
| 36 | + subject.render(data: @users[0], |
| 37 | + include: 'posts', |
| 38 | + cache: cache) |
| 39 | + # Actual call on warm cache. |
| 40 | + actual = subject.render(data: @users[0], |
| 41 | + include: 'posts', |
| 42 | + cache: cache) |
| 43 | + expected = { |
| 44 | + data: { |
| 45 | + type: 'users', |
| 46 | + id: '1', |
| 47 | + attributes: { |
| 48 | + name: 'User 1', |
| 49 | + address: '123 Example st.' |
| 50 | + }, |
| 51 | + relationships: { |
| 52 | + posts: { |
| 53 | + data: [{ type: 'posts', id: '2' }], |
| 54 | + links: { |
| 55 | + self: 'http://api.example.com/users/1/relationships/posts', |
| 56 | + related: { |
| 57 | + href: 'http://api.example.com/users/1/posts', |
| 58 | + meta: { |
| 59 | + do_not_use: true |
| 60 | + } |
| 61 | + } |
| 62 | + }, |
| 63 | + meta: { |
| 64 | + deleted_posts: 5 |
| 65 | + } |
| 66 | + } |
| 67 | + }, |
| 68 | + links: { |
| 69 | + self: 'http://api.example.com/users/1' |
| 70 | + }, |
| 71 | + meta: { |
| 72 | + user_meta: 'is_meta' |
| 73 | + } |
| 74 | + }, |
| 75 | + included: [ |
| 76 | + { |
| 77 | + type: 'posts', |
| 78 | + id: '2', |
| 79 | + attributes: { |
| 80 | + title: 'Post 2', |
| 81 | + date: 'today' |
| 82 | + }, |
| 83 | + relationships: { |
| 84 | + author: { |
| 85 | + links: { |
| 86 | + self: 'http://api.example.com/posts/2/relationships/author', |
| 87 | + related: 'http://api.example.com/posts/2/author' |
| 88 | + }, |
| 89 | + meta: { |
| 90 | + author_active: true |
| 91 | + } |
| 92 | + } |
| 93 | + } |
| 94 | + } |
| 95 | + ] |
| 96 | + } |
| 97 | + |
| 98 | + expect(JSON.parse(actual.to_json)).to eq(JSON.parse(expected.to_json)) |
| 99 | + expect(actual[:data]).to be_a(JSONAPI::Renderer::CachedResourcesProcessor::JSONString) |
| 100 | + end |
| 101 | +end |
0 commit comments