Skip to content

Commit 8b00d09

Browse files
authored
Add assert_in_body/assert_not_in_body (rails#54938)
* Add assert_in_body/assert_not_in_body As a simple encapsulation of checking a response body for a piece of text without having to go through a heavy-duty DOM operation. * Add CHANGELOG entry * Appease Rubocop * Escape text so it doesnt trigger regular expressions inadvertedly
1 parent 17cde11 commit 8b00d09

File tree

3 files changed

+24
-0
lines changed

3 files changed

+24
-0
lines changed

actionpack/CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
* Add assert_in_body/assert_not_in_body as the simplest way to check if a piece of text is in the response body.
2+
3+
*DHH*
4+
15
* Include cookie name when calculating maximum allowed size.
26

37
*Hartley McGuire*

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

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,20 @@ def assert_redirected_to(url_options = {}, options = {}, message = nil)
7171
assert_operator redirect_expected, :===, redirect_is, message
7272
end
7373

74+
# Asserts that the given +text+ is present somewhere in the response body.
75+
#
76+
# assert_in_body fixture(:name).description
77+
def assert_in_body(text)
78+
assert_match(/#{Regexp.escape(text)}/, @response.body)
79+
end
80+
81+
# Asserts that the given +text+ is not present anywhere in the response body.
82+
#
83+
# assert_not_in_body fixture(:name).description
84+
def assert_not_in_body(text)
85+
assert_no_match(/#{Regexp.escape(text)}/, @response.body)
86+
end
87+
7488
private
7589
# Proxy to to_param if the object will respond to it.
7690
def parameterize(value)

actionpack/test/controller/action_pack_assertions_test.rb

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -496,6 +496,12 @@ def test_assert_response_failure_response_with_no_exception
496496
assert_response 500
497497
assert_equal "Boom", response.body
498498
end
499+
500+
def test_assert_in_body
501+
post :raise_exception_on_get
502+
assert_in_body "request method: POST"
503+
assert_not_in_body "request method: GET"
504+
end
499505
end
500506

501507
class ActionPackHeaderTest < ActionController::TestCase

0 commit comments

Comments
 (0)