Skip to content

Commit

Permalink
Respond with 422 for non-GET JS requests with errors
Browse files Browse the repository at this point in the history
Much like HTML responses, JS will respond with a 422 Unprocessable
Entity for non-GET requests if the given resource contains errors, so it
is consistent with all other formats going forward.

Closes #159.
  • Loading branch information
carlosantoniodasilva committed Jan 16, 2021
1 parent 8f4de70 commit ca2ab74
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 1 deletion.
2 changes: 1 addition & 1 deletion CHANGELOG.md
@@ -1,6 +1,6 @@
## Unreleased

* Responding to an `HTML` request that has errors on the resource now sets the status to `422 Unprocessable Entity`. (instead of the default of `200 OK`.) This makes it more consistent with other statuses more commonly used in APIs (JSON/XML for example), and works by default with Turbo/Hotwire. Note that this change may break your application if you're relying on the previous 2xx status to handle error cases.
* Responding to an `HTML` or `JS` request that has errors on the resource now sets the status to `422 Unprocessable Entity`. (instead of the default of `200 OK`.) This makes it more consistent with other statuses more commonly used in APIs (JSON/XML for example), and works by default with Turbo/Hotwire which expects a 422 on form error HTML responses. Note that this change may break your application if you're relying on the previous 2xx status to handle error cases.
* Add support for Ruby 3.0, drop support for Ruby < 2.5.
* Add support for Rails 6.1, drop support for Rails < 5.2.
* Move CI to GitHub Actions.
Expand Down
2 changes: 2 additions & 0 deletions lib/action_controller/responder.rb
Expand Up @@ -236,6 +236,8 @@ def resource_location
def default_render
if @default_response
@default_response.call(options)
elsif !get? && has_errors?
controller.render(options.merge(status: :unprocessable_entity))
else
controller.render(options)
end
Expand Down
11 changes: 11 additions & 0 deletions test/action_controller/respond_with_test.rb
Expand Up @@ -170,6 +170,17 @@ def test_using_resource_with_js_simply_tries_to_render_the_template
get :using_resource
assert_equal "text/javascript", @response.media_type
assert_equal "alert(\"Hi\");", @response.body
assert_equal 200, @response.status
end

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

def test_using_hash_resource_with_js_raises_an_error_if_template_cant_be_found
Expand Down

0 comments on commit ca2ab74

Please sign in to comment.