active_model_serializers/test/adapter/attributes_test.rb
Ian C. Anderson 2423ca4999 Support key transformation for Attributes adapter (#1889)
The `:attributes` adapter is the default one, but it did not support
key transformation. This was very surprising behavior, since the
"Configuration Options" page in the guides didn't mention that this
behavior was not supported by the attributes adapter.

This commit adds key transform support to the attributes adapter, and
adds documentation about the default transform for the attributes
adapter (which is `:unaltered`).

This commit also handles arrays when transforming keys, which was needed
in the case where you're serializing a collection with the Attributes
adapter. With the JSON adapter, it was always guaranteed to pass a hash
to the KeyTransform functions because of the top-level key. Since there
is no top-level key for the Attributes adapter, the return value could
be an array.
2016-08-25 15:21:27 -04:00

44 lines
1.2 KiB
Ruby

require 'test_helper'
module ActiveModelSerializers
module Adapter
class AttributesTest < ActiveSupport::TestCase
class Person
include ActiveModel::Model
include ActiveModel::Serialization
attr_accessor :first_name, :last_name
end
class PersonSerializer < ActiveModel::Serializer
attributes :first_name, :last_name
end
def setup
ActionController::Base.cache_store.clear
end
def test_serializable_hash
person = Person.new(first_name: 'Arthur', last_name: 'Dent')
serializer = PersonSerializer.new(person)
adapter = ActiveModelSerializers::Adapter::Attributes.new(serializer)
assert_equal({ first_name: 'Arthur', last_name: 'Dent' },
adapter.serializable_hash)
end
def test_serializable_hash_with_transform_key_casing
person = Person.new(first_name: 'Arthur', last_name: 'Dent')
serializer = PersonSerializer.new(person)
adapter = ActiveModelSerializers::Adapter::Attributes.new(
serializer,
key_transform: :camel_lower
)
assert_equal({ firstName: 'Arthur', lastName: 'Dent' },
adapter.serializable_hash)
end
end
end
end