Skip to content

Commit

Permalink
Respect status given to respond_with when responding with errors
Browse files Browse the repository at this point in the history
Otherwise we would enforce `422 Unprocessable Entity` even if there was
a `status` provided, now we'll respect that status first, and use `422`
as default/fallback.
  • Loading branch information
carlosantoniodasilva committed Jan 27, 2023
1 parent 2b23c7c commit 01e9531
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 2 deletions.
2 changes: 1 addition & 1 deletion lib/action_controller/responder.rb
Original file line number Diff line number Diff line change
Expand Up @@ -238,7 +238,7 @@ def default_render
if @default_response
@default_response.call(options)
elsif !get? && has_errors?
controller.render(options.merge(status: :unprocessable_entity))
controller.render({ status: :unprocessable_entity }.merge!(options))
else
controller.render(options)
end
Expand Down
16 changes: 15 additions & 1 deletion test/action_controller/respond_with_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ def to_json(*); super; end

respond_to :html, :json, :touch
respond_to :xml, except: :using_resource_with_block
respond_to :js, only: [ :using_resource_with_block, :using_resource, "using_hash_resource" ]
respond_to :js, only: [ :using_resource_with_block, :using_resource, "using_hash_resource", :using_resource_with_status ]

def using_resource
respond_with(resource)
Expand All @@ -20,6 +20,10 @@ def using_hash_resource
respond_with(result: resource)
end

def using_resource_with_status
respond_with(resource, status: 418, template: "respond_with/using_resource")
end

def using_resource_with_block
respond_with(resource) do |format|
format.csv { render body: "CSV", content_type: "text/csv" }
Expand Down Expand Up @@ -183,6 +187,16 @@ def test_using_resource_for_post_with_js_renders_the_template_and_yields_unproce
assert_equal 422, @response.status
end

def test_using_resource_for_post_with_js_renders_the_template_and_yields_given_status_on_failure
@request.accept = "text/javascript"
errors = { name: :invalid }
Customer.any_instance.stubs(:errors).returns(errors)
post :using_resource_with_status
assert_equal "text/javascript", @response.media_type
assert_equal "alert(\"Hi\");", @response.body
assert_equal 418, @response.status
end

def test_using_hash_resource_with_js_raises_an_error_if_template_cant_be_found
@request.accept = "text/javascript"
assert_raise ActionView::MissingTemplate do
Expand Down

0 comments on commit 01e9531

Please sign in to comment.