From 7af198653d052044c72012d10f9b0ae1a4c2f394 Mon Sep 17 00:00:00 2001 From: Lucas Hosseini Date: Tue, 12 Jan 2016 13:42:44 +0100 Subject: [PATCH] Add tests for conditional attributes/associations. --- test/serializers/associations_test.rb | 23 +++++++++++++++++++++++ test/serializers/attribute_test.rb | 25 ++++++++++++++++++++++++- 2 files changed, 47 insertions(+), 1 deletion(-) diff --git a/test/serializers/associations_test.rb b/test/serializers/associations_test.rb index 4778fb2e..aa0cae08 100644 --- a/test/serializers/associations_test.rb +++ b/test/serializers/associations_test.rb @@ -238,6 +238,29 @@ module ActiveModel end end end + + def test_conditional_associations + serializer = Class.new(ActiveModel::Serializer) do + belongs_to :if_assoc_included, if: :true + belongs_to :if_assoc_excluded, if: :false + belongs_to :unless_assoc_included, unless: :false + belongs_to :unless_assoc_excluded, unless: :true + + def true + true + end + + def false + false + end + end + + model = ::Model.new + hash = serializable(model, serializer: serializer).serializable_hash + expected = { if_assoc_included: nil, unless_assoc_included: nil } + + assert_equal(expected, hash) + end end end end diff --git a/test/serializers/attribute_test.rb b/test/serializers/attribute_test.rb index 112e7ec5..c675e0ac 100644 --- a/test/serializers/attribute_test.rb +++ b/test/serializers/attribute_test.rb @@ -4,7 +4,7 @@ module ActiveModel class Serializer class AttributeTest < ActiveSupport::TestCase def setup - @blog = Blog.new({ id: 1, name: 'AMS Hints', type: 'stuff' }) + @blog = Blog.new(id: 1, name: 'AMS Hints', type: 'stuff') @blog_serializer = AlternateBlogSerializer.new(@blog) end @@ -95,6 +95,29 @@ module ActiveModel assert_equal(expected, hash) end + + def test_conditional_attributes + serializer = Class.new(ActiveModel::Serializer) do + attribute :if_attribute_included, if: :true + attribute :if_attribute_excluded, if: :false + attribute :unless_attribute_included, unless: :false + attribute :unless_attribute_excluded, unless: :true + + def true + true + end + + def false + false + end + end + + model = ::Model.new + hash = serializable(model, serializer: serializer).serializable_hash + expected = { if_attribute_included: nil, unless_attribute_included: nil } + + assert_equal(expected, hash) + end end end end