Skip to content

Commit 5e5211e

Browse files
committed
assert_response: unwrap exceptions captured by ShowExceptions
If we get back a different response status from the one we were expecting, and an exception was rescued, it's likely to be relevant. Before: Expected response to be a <200> but was a <500: Internal Server Error>. After: Expected response to be a <200> but was a <500: Internal Server Error>. Exception while processing request: RuntimeError: foo <backtrace>
1 parent ce5f181 commit 5e5211e

File tree

2 files changed

+25
-2
lines changed

2 files changed

+25
-2
lines changed

actionpack/lib/action_dispatch/testing/assertions/response.rb

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -87,15 +87,25 @@ def normalize_argument_to_redirection(fragment)
8787
end
8888

8989
def generate_response_message(expected, actual = @response.response_code)
90-
(+"Expected response to be a <#{code_with_name(expected)}>,"\
91-
" but was a <#{code_with_name(actual)}>").concat(location_if_redirected).concat(response_body_if_short)
90+
lambda do
91+
(+"Expected response to be a <#{code_with_name(expected)}>,"\
92+
" but was a <#{code_with_name(actual)}>").
93+
concat(location_if_redirected).
94+
concat(exception_if_present).
95+
concat(response_body_if_short)
96+
end
9297
end
9398

9499
def response_body_if_short
95100
return "" if @response.body.size > 500
96101
"\nResponse body: #{@response.body}"
97102
end
98103

104+
def exception_if_present
105+
return "" unless ex = @request&.env&.[]("action_dispatch.exception")
106+
"\n\nException while processing request: #{Minitest::UnexpectedError.new(ex).message}\n"
107+
end
108+
99109
def location_if_redirected
100110
return "" unless @response.redirection? && @response.location.present?
101111
location = normalize_argument_to_redirection(@response.location)

actionpack/test/assertions/response_assertions_test.rb

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,19 @@ def test_error_message_does_not_show_long_response_body
136136
" but was a <400: Bad Request>"
137137
assert_match expected, error.message
138138
end
139+
140+
def test_error_message_shows_rescued_exception
141+
@response = ActionDispatch::Response.new
142+
@response.status = 500
143+
144+
@request = ActionDispatch::Request.new("action_dispatch.exception" => RuntimeError.new("example error"))
145+
146+
error = assert_raises(Minitest::Assertion) { assert_response 200 }
147+
expected = "Expected response to be a <200: OK>,"\
148+
" but was a <500: Internal Server Error>\n\n"\
149+
"Exception while processing request: RuntimeError: example error\n"
150+
assert_match expected, error.message
151+
end
139152
end
140153
end
141154
end

0 commit comments

Comments
 (0)