From 2524cf404ce943eca8a5f2d173188fd0cf2ac8b9 Mon Sep 17 00:00:00 2001 From: Jakub Suder Date: Sun, 29 Aug 2010 16:10:31 +0200 Subject: fixed some issues with JSON encoding - as_json in ActiveModel should return a hash and handle :only/:except/:methods options - Array and Hash should call as_json on their elements - json methods should not modify options argument [#5374 state:committed] Signed-off-by: Jeremy Kemper --- .../serializeration/json_serialization_test.rb | 27 ++++++++++++++++++++++ 1 file changed, 27 insertions(+) (limited to 'activemodel/test/cases/serializeration/json_serialization_test.rb') diff --git a/activemodel/test/cases/serializeration/json_serialization_test.rb b/activemodel/test/cases/serializeration/json_serialization_test.rb index 3bc39bb06d..20d123ef0b 100644 --- a/activemodel/test/cases/serializeration/json_serialization_test.rb +++ b/activemodel/test/cases/serializeration/json_serialization_test.rb @@ -116,5 +116,32 @@ class JsonSerializationTest < ActiveModel::TestCase assert_equal hash.to_json, car.errors.to_json end + test "serializable_hash should not modify options passed in argument" do + options = { :except => :name } + @contact.serializable_hash(options) + + assert_nil options[:only] + assert_equal :name, options[:except] + end + + test "as_json should return a hash" do + json = @contact.as_json + + assert_kind_of Hash, json + assert_kind_of Hash, json['contact'] + %w(name age created_at awesome preferences).each do |field| + assert_equal @contact.send(field), json['contact'][field] + end + end + + test "custom as_json should be honored when generating json" do + def @contact.as_json(options); { :name => name, :created_at => created_at }; end + json = @contact.to_json + + assert_match %r{"name":"Konata Izumi"}, json + assert_match %r{"created_at":#{ActiveSupport::JSON.encode(Time.utc(2006, 8, 1))}}, json + assert_no_match %r{"awesome":}, json + assert_no_match %r{"preferences":}, json + end end -- cgit v1.2.3