From a0a68ecbb22dacf5111198e72e3a803e7c965881 Mon Sep 17 00:00:00 2001 From: Denis Odorcic Date: Mon, 10 Oct 2011 01:42:12 -0400 Subject: JSON responder should return errors with :error root --- .../lib/action_controller/metal/responder.rb | 10 ++++++++- actionpack/test/controller/mime_responds_test.rb | 26 ++++++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/actionpack/lib/action_controller/metal/responder.rb b/actionpack/lib/action_controller/metal/responder.rb index 3794e277f6..c7827309dd 100644 --- a/actionpack/lib/action_controller/metal/responder.rb +++ b/actionpack/lib/action_controller/metal/responder.rb @@ -253,7 +253,7 @@ module ActionController #:nodoc: end def display_errors - controller.render format => resource.errors, :status => :unprocessable_entity + controller.render format => resource_errors, :status => :unprocessable_entity end # Check whether the resource has errors. @@ -286,5 +286,13 @@ module ActionController #:nodoc: def empty_json_resource "{}" end + + def resource_errors + respond_to?("#{format}_resource_errors") ? send("#{format}_resource_errors") : resource.errors + end + + def json_resource_errors + {:errors => resource.errors} + end end end diff --git a/actionpack/test/controller/mime_responds_test.rb b/actionpack/test/controller/mime_responds_test.rb index afb2d39955..afdab30eaf 100644 --- a/actionpack/test/controller/mime_responds_test.rb +++ b/actionpack/test/controller/mime_responds_test.rb @@ -745,6 +745,20 @@ class RespondWithControllerTest < ActionController::TestCase end end + def test_using_resource_for_post_with_json_yields_unprocessable_entity_on_failure + with_test_route_set do + @request.accept = "application/json" + errors = { :name => :invalid } + Customer.any_instance.stubs(:errors).returns(errors) + post :using_resource + assert_equal "application/json", @response.content_type + assert_equal 422, @response.status + errors = {:errors => errors} + assert_equal errors.to_json, @response.body + assert_nil @response.location + end + end + def test_using_resource_for_put_with_html_redirects_on_success with_test_route_set do put :using_resource @@ -808,6 +822,18 @@ class RespondWithControllerTest < ActionController::TestCase assert_nil @response.location end + def test_using_resource_for_put_with_json_yields_unprocessable_entity_on_failure + @request.accept = "application/json" + errors = { :name => :invalid } + Customer.any_instance.stubs(:errors).returns(errors) + put :using_resource + assert_equal "application/json", @response.content_type + assert_equal 422, @response.status + errors = {:errors => errors} + assert_equal errors.to_json, @response.body + assert_nil @response.location + end + def test_using_resource_for_delete_with_html_redirects_on_success with_test_route_set do Customer.any_instance.stubs(:destroyed?).returns(true) -- cgit v1.2.3