From 8f5ebfac03ad32d7f4053f7284165c7a033c3664 Mon Sep 17 00:00:00 2001 From: ccocchi Date: Thu, 26 Jul 2012 15:24:20 +0200 Subject: [PATCH] Add test for RablRails#render with instance variables --- lib/rabl-rails/renderer.rb | 12 +++++++++++- test/render_test.rb | 16 ++++++++++++---- 2 files changed, 23 insertions(+), 5 deletions(-) diff --git a/lib/rabl-rails/renderer.rb b/lib/rabl-rails/renderer.rb index 2a04493..168b409 100644 --- a/lib/rabl-rails/renderer.rb +++ b/lib/rabl-rails/renderer.rb @@ -28,7 +28,7 @@ module RablRails end # - # Context class to emulate normal rendering view + # Context class to emulate normal Rails view # context # class Context @@ -66,6 +66,16 @@ module RablRails # Default render format is JSON, but can be changed via # an option: { format: 'xml' } # + # If template includes uses of instance variables (usually + # defined in the controller), you can passed them as locals + # options. + # For example, if you have this template: + # object :@user + # node(:read) { |u| u.has_read?(@post) } + # + # Your method call should look like this: + # RablRails.render(user, 'users/show', locals: { post: Post.new }) + # def render(object, template, options = {}) object = options[:locals].delete(:object) if !object && options[:locals] diff --git a/test/render_test.rb b/test/render_test.rb index c9dd417..8108f7c 100644 --- a/test/render_test.rb +++ b/test/render_test.rb @@ -17,7 +17,6 @@ class RenderTest < ActiveSupport::TestCase attributes :name } end - assert_equal %q({"user":{"name":"Marty"}}), RablRails.render(nil, 'nil', locals: { object: @user }, view_path: @tmp_path) end @@ -28,12 +27,21 @@ class RenderTest < ActiveSupport::TestCase attributes :id, :name } end - assert_equal %q({"user":{"id":1,"name":"Marty"}}), RablRails.render(@user, 'show', view_path: @tmp_path) end test "raise error if template is not found" do - assert_raises(RablRails::Renderer::TemplateNotFound) { RablRails.render(@user, 'show') } + assert_raises(RablRails::Renderer::TemplateNotFound) { RablRails.render(@user, 'not_found') } + end + + test "instance variables can be passed via options[:locals]" do + File.open(@tmp_path + "instance.json.rabl", "w") do |f| + f.puts %q{ + object false + node(:username) { |_| @user.name } + } + end + assert_equal %q({"username":"Marty"}), RablRails.render(nil, 'instance', view_path: @tmp_path, locals: { user: @user }) end test "handle path for extends" do @@ -43,7 +51,7 @@ class RenderTest < ActiveSupport::TestCase extends 'base' } end - + File.open(@tmp_path + "base.json.rabl", "w") do |f| f.puts %q{ attribute :name, as: :extended_name