File: jbuilder_template_test.rb

package info (click to toggle)
ruby-jbuilder 2.12.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 304 kB
  • sloc: ruby: 2,112; makefile: 3
file content (417 lines) | stat: -rw-r--r-- 13,296 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
require "test_helper"
require "action_view/testing/resolvers"

class JbuilderTemplateTest < ActiveSupport::TestCase
  POST_PARTIAL = <<-JBUILDER
    json.extract! post, :id, :body
    json.author do
      first_name, last_name = post.author_name.split(nil, 2)
      json.first_name first_name
      json.last_name last_name
    end
  JBUILDER

  COLLECTION_PARTIAL = <<-JBUILDER
    json.extract! collection, :id, :name
  JBUILDER

  RACER_PARTIAL = <<-JBUILDER
    json.extract! racer, :id, :name
  JBUILDER

  PARTIALS = {
    "_partial.json.jbuilder"      => "json.content content",
    "_post.json.jbuilder"         => POST_PARTIAL,
    "racers/_racer.json.jbuilder" => RACER_PARTIAL,
    "_collection.json.jbuilder"   => COLLECTION_PARTIAL,

    # Ensure we find only Jbuilder partials from within Jbuilder templates.
    "_post.html.erb" => "Hello world!"
  }

  AUTHORS = [ "David Heinemeier Hansson", "Pavel Pravosud" ].cycle
  POSTS   = (1..10).collect { |i| Post.new(i, "Post ##{i}", AUTHORS.next) }

  setup { Rails.cache.clear }

  test "basic template" do
    result = render('json.content "hello"')
    assert_equal "hello", result["content"]
  end

  test "partial by name with top-level locals" do
    result = render('json.partial! "partial", content: "hello"')
    assert_equal "hello", result["content"]
  end

  test "partial by name with nested locals" do
    result = render('json.partial! "partial", locals: { content: "hello" }')
    assert_equal "hello", result["content"]
  end

  test "partial by options containing nested locals" do
    result = render('json.partial! partial: "partial", locals: { content: "hello" }')
    assert_equal "hello", result["content"]
  end

  test "partial by options containing top-level locals" do
    result = render('json.partial! partial: "partial", content: "hello"')
    assert_equal "hello", result["content"]
  end

  test "partial for Active Model" do
    result = render('json.partial! @racer', racer: Racer.new(123, "Chris Harris"))
    assert_equal 123, result["id"]
    assert_equal "Chris Harris", result["name"]
  end

  test "partial collection by name with symbol local" do
    result = render('json.partial! "post", collection: @posts, as: :post', posts: POSTS)
    assert_equal 10, result.count
    assert_equal "Post #5", result[4]["body"]
    assert_equal "Heinemeier Hansson", result[2]["author"]["last_name"]
    assert_equal "Pavel", result[5]["author"]["first_name"]
  end

  test "partial collection by name with caching" do
    result = render('json.partial! "post", collection: @posts, cached: true, as: :post', posts: POSTS)
    assert_equal 10, result.count
    assert_equal "Post #5", result[4]["body"]
    assert_equal "Heinemeier Hansson", result[2]["author"]["last_name"]
    assert_equal "Pavel", result[5]["author"]["first_name"]
  end

  test "partial collection by name with string local" do
    result = render('json.partial! "post", collection: @posts, as: "post"', posts: POSTS)
    assert_equal 10, result.count
    assert_equal "Post #5", result[4]["body"]
    assert_equal "Heinemeier Hansson", result[2]["author"]["last_name"]
    assert_equal "Pavel", result[5]["author"]["first_name"]
  end

  test "partial collection by options" do
    result = render('json.partial! partial: "post", collection: @posts, as: :post', posts: POSTS)
    assert_equal 10, result.count
    assert_equal "Post #5", result[4]["body"]
    assert_equal "Heinemeier Hansson", result[2]["author"]["last_name"]
    assert_equal "Pavel", result[5]["author"]["first_name"]
  end

  test "nil partial collection by name" do
    assert_equal [], render('json.partial! "post", collection: @posts, as: :post', posts: nil)
  end

  test "nil partial collection by options" do
    assert_equal [], render('json.partial! partial: "post", collection: @posts, as: :post', posts: nil)
  end

  test "array of partials" do
    result = render('json.array! @posts, partial: "post", as: :post', posts: POSTS)
    assert_equal 10, result.count
    assert_equal "Post #5", result[4]["body"]
    assert_equal "Heinemeier Hansson", result[2]["author"]["last_name"]
    assert_equal "Pavel", result[5]["author"]["first_name"]
  end

  test "empty array of partials from nil collection" do
    assert_equal [], render('json.array! @posts, partial: "post", as: :post', posts: nil)
  end

  test "array of partials under key" do
    result = render('json.posts @posts, partial: "post", as: :post', posts: POSTS)
    assert_equal 10, result["posts"].count
    assert_equal "Post #5", result["posts"][4]["body"]
    assert_equal "Heinemeier Hansson", result["posts"][2]["author"]["last_name"]
    assert_equal "Pavel", result["posts"][5]["author"]["first_name"]
  end

  test "empty array of partials under key from nil collection" do
    result = render('json.posts @posts, partial: "post", as: :post', posts: nil)
    assert_equal [], result["posts"]
  end

  test "object fragment caching" do
    render(<<-JBUILDER)
      json.cache! "cache-key" do
        json.name "Hit"
      end
    JBUILDER

    hit = render('json.cache! "cache-key" do; end')
    assert_equal "Hit", hit["name"]
  end

  test "conditional object fragment caching" do
    render(<<-JBUILDER)
      json.cache_if! true, "cache-key" do
        json.a "Hit"
      end

      json.cache_if! false, "cache-key" do
        json.b "Hit"
      end
    JBUILDER

    result = render(<<-JBUILDER)
      json.cache_if! true, "cache-key" do
        json.a "Miss"
      end

      json.cache_if! false, "cache-key" do
        json.b "Miss"
      end
    JBUILDER

    assert_equal "Hit", result["a"]
    assert_equal "Miss", result["b"]
  end

  test "object fragment caching with expiry" do
    travel_to Time.iso8601("2018-05-12T11:29:00-04:00")

    render <<-JBUILDER
      json.cache! "cache-key", expires_in: 1.minute do
        json.name "Hit"
      end
    JBUILDER

    travel 30.seconds

    result = render(<<-JBUILDER)
      json.cache! "cache-key", expires_in: 1.minute do
        json.name "Miss"
      end
    JBUILDER

    assert_equal "Hit", result["name"]

    travel 31.seconds

    result = render(<<-JBUILDER)
      json.cache! "cache-key", expires_in: 1.minute do
        json.name "Miss"
      end
    JBUILDER

    assert_equal "Miss", result["name"]
  end

  test "object root caching" do
    render <<-JBUILDER
      json.cache_root! "cache-key" do
        json.name "Hit"
      end
    JBUILDER

    assert_equal JSON.dump(name: "Hit"), Rails.cache.read("jbuilder/root/cache-key")

    result = render(<<-JBUILDER)
      json.cache_root! "cache-key" do
        json.name "Miss"
      end
    JBUILDER

    assert_equal "Hit", result["name"]
  end

  test "array fragment caching" do
    render <<-JBUILDER
      json.cache! "cache-key" do
        json.array! %w[ a b c ]
      end
    JBUILDER

    assert_equal %w[ a b c ], render('json.cache! "cache-key" do; end')
  end

  test "array root caching" do
    render <<-JBUILDER
      json.cache_root! "cache-key" do
        json.array! %w[ a b c ]
      end
    JBUILDER

    assert_equal JSON.dump(%w[ a b c ]), Rails.cache.read("jbuilder/root/cache-key")

    assert_equal %w[ a b c ], render(<<-JBUILDER)
      json.cache_root! "cache-key" do
        json.array! %w[ d e f ]
      end
    JBUILDER
  end

  test "failing to cache root after JSON structures have been defined" do
    assert_raises ActionView::Template::Error, "cache_root! can't be used after JSON structures have been defined" do
      render <<-JBUILDER
        json.name "Kaboom"
        json.cache_root! "cache-key" do
          json.name "Miss"
        end
      JBUILDER
    end
  end

  test "empty fragment caching" do
    render 'json.cache! "nothing" do; end'

    result = nil

    assert_nothing_raised do
      result = render(<<-JBUILDER)
        json.foo "bar"
        json.cache! "nothing" do; end
      JBUILDER
    end

    assert_equal "bar", result["foo"]
  end

  test "cache instrumentation" do
    payloads = {}

    ActiveSupport::Notifications.subscribe("read_fragment.action_controller") { |*args| payloads[:read] = args.last }
    ActiveSupport::Notifications.subscribe("write_fragment.action_controller") { |*args| payloads[:write] = args.last }

    render <<-JBUILDER
      json.cache! "cache-key" do
        json.name "Cache"
      end
    JBUILDER

    assert_equal "jbuilder/cache-key", payloads[:read][:key]
    assert_equal "jbuilder/cache-key", payloads[:write][:key]
  end

  test "camelized keys" do
    result = render(<<-JBUILDER)
      json.key_format! camelize: [:lower]
      json.first_name "David"
    JBUILDER

    assert_equal "David", result["firstName"]
  end

  if JbuilderTemplate::CollectionRenderer.supported?
    test "returns an empty array for an empty collection" do
      result = render('json.array! @posts, partial: "post", as: :post, cached: true', posts: [])

      # Do not use #assert_empty as it is important to ensure that the type of the JSON result is an array.
      assert_equal [], result
    end

    test "works with an enumerable object" do
      enumerable_class = Class.new do
        include Enumerable

        def each(&block)
          [].each(&block)
        end
      end

      result = render('json.array! @posts, partial: "post", as: :post, cached: true', posts: enumerable_class.new)

      # Do not use #assert_empty as it is important to ensure that the type of the JSON result is an array.
      assert_equal [], result
    end

    test "supports the cached: true option" do
      result = render('json.array! @posts, partial: "post", as: :post, cached: true', posts: POSTS)

      assert_equal 10, result.count
      assert_equal "Post #5", result[4]["body"]
      assert_equal "Heinemeier Hansson", result[2]["author"]["last_name"]
      assert_equal "Pavel", result[5]["author"]["first_name"]

      expected = {
        "id" => 1,
        "body" => "Post #1",
        "author" => {
          "first_name" => "David",
          "last_name" => "Heinemeier Hansson"
        }
      }

      assert_equal expected, Rails.cache.read("post-1")

      result = render('json.array! @posts, partial: "post", as: :post, cached: true', posts: POSTS)

      assert_equal 10, result.count
      assert_equal "Post #5", result[4]["body"]
      assert_equal "Heinemeier Hansson", result[2]["author"]["last_name"]
      assert_equal "Pavel", result[5]["author"]["first_name"]
    end

    test "supports the cached: ->() {} option" do
      result = render('json.array! @posts, partial: "post", as: :post, cached: ->(post) { [post, "foo"] }', posts: POSTS)

      assert_equal 10, result.count
      assert_equal "Post #5", result[4]["body"]
      assert_equal "Heinemeier Hansson", result[2]["author"]["last_name"]
      assert_equal "Pavel", result[5]["author"]["first_name"]

      expected = {
        "id" => 1,
        "body" => "Post #1",
        "author" => {
          "first_name" => "David",
          "last_name" => "Heinemeier Hansson"
        }
      }

      assert_equal expected, Rails.cache.read("post-1/foo")

      result = render('json.array! @posts, partial: "post", as: :post, cached: ->(post) { [post, "foo"] }', posts: POSTS)

      assert_equal 10, result.count
      assert_equal "Post #5", result[4]["body"]
      assert_equal "Heinemeier Hansson", result[2]["author"]["last_name"]
      assert_equal "Pavel", result[5]["author"]["first_name"]
    end

    test "raises an error on a render call with the :layout option" do
      error = assert_raises NotImplementedError do
        render('json.array! @posts, partial: "post", as: :post, layout: "layout"', posts: POSTS)
      end

      assert_equal "The `:layout' option is not supported in collection rendering.", error.message
    end

    test "raises an error on a render call with the :spacer_template option" do
      error = assert_raises NotImplementedError do
        render('json.array! @posts, partial: "post", as: :post, spacer_template: "template"', posts: POSTS)
      end

      assert_equal "The `:spacer_template' option is not supported in collection rendering.", error.message
    end
  end

  private
    def render(*args)
      JSON.load render_without_parsing(*args)
    end

    def render_without_parsing(source, assigns = {})
      view = build_view(fixtures: PARTIALS.merge("source.json.jbuilder" => source), assigns: assigns)
      view.render(template: "source")
    end

    def build_view(options = {})
      resolver = ActionView::FixtureResolver.new(options.fetch(:fixtures))
      lookup_context = ActionView::LookupContext.new([ resolver ], {}, [""])
      controller = ActionView::TestCase::TestController.new

      # TODO: Use with_empty_template_cache unconditionally after dropping support for Rails <6.0.
      view = if ActionView::Base.respond_to?(:with_empty_template_cache)
        ActionView::Base.with_empty_template_cache.new(lookup_context, options.fetch(:assigns, {}), controller)
      else
        ActionView::Base.new(lookup_context, options.fetch(:assigns, {}), controller)
      end

      def view.view_cache_dependencies; []; end
      def view.combined_fragment_cache_key(key) [ key ] end
      def view.cache_fragment_name(key, *) key end
      def view.fragment_name_with_digest(key) key end

      view
    end
end