Improve assert_response helper

When the check is failed, print the actual response body if it's not too large.
This could improve productivity when writing new tests.

Before:

```
ThemeEditorIntegrationTest#test_whatever
    Expected response to be a <200: ok>, but was a <422: Unprocessable Entity>.
Expected: 200
  Actual: 422
```

After:

```
ThemeEditorIntegrationTest#test_whatever
    Expected response to be a <200: ok>, but was a <422: Unprocessable Entity>.
Expected: 200
  Actual: 422
Response body: {"errors":["Invalid settings object for section '1'"]}
```
This commit is contained in:
Kir Shatrov 2016-09-12 17:56:38 -04:00
parent cf5f55cd30
commit bc3b0e7292
2 changed files with 29 additions and 2 deletions

@ -79,7 +79,12 @@ def normalize_argument_to_redirection(fragment)
def generate_response_message(expected, actual = @response.response_code)
"Expected response to be a <#{code_with_name(expected)}>,"\
" but was a <#{code_with_name(actual)}>"
.concat location_if_redirected
.concat(location_if_redirected).concat(response_body_if_short)
end
def response_body_if_short
return "" if @response.body.size > 500
"\nResponse body: #{@response.body}"
end
def location_if_redirected

@ -6,10 +6,11 @@ module Assertions
class ResponseAssertionsTest < ActiveSupport::TestCase
include ResponseAssertions
FakeResponse = Struct.new(:response_code, :location) do
FakeResponse = Struct.new(:response_code, :location, :body) do
def initialize(*)
super
self.location ||= "http://test.example.com/posts"
self.body ||= ""
end
[:successful, :not_found, :redirection, :server_error].each do |sym|
@ -112,6 +113,27 @@ def test_error_message_shows_302_redirect_when_302_asserted_for_301
" redirect to <http://test.host/posts/redirect/2>"
assert_match expected, error.message
end
def test_error_message_shows_short_response_body
@response = ActionDispatch::Response.new
@response.status = 400
@response.body = "not too long"
error = assert_raises(Minitest::Assertion) { assert_response 200 }
expected = "Expected response to be a <200: OK>,"\
" but was a <400: Bad Request>" \
"\nResponse body: not too long"
assert_match expected, error.message
end
def test_error_message_does_not_show_long_response_body
@response = ActionDispatch::Response.new
@response.status = 400
@response.body = "not too long" * 50
error = assert_raises(Minitest::Assertion) { assert_response 200 }
expected = "Expected response to be a <200: OK>,"\
" but was a <400: Bad Request>"
assert_match expected, error.message
end
end
end
end