Skip to content

Commit 767ecc4

Browse files
committed
Add ability to match exception messages to assert_raises assertion
1 parent 6f3c966 commit 767ecc4

File tree

3 files changed

+46
-0
lines changed

3 files changed

+46
-0
lines changed

activesupport/CHANGELOG.md

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,22 @@
1+
* Add ability to match exception messages to `assert_raises` assertion
2+
3+
Instead of this
4+
```ruby
5+
error = assert_raises(ArgumentError) do
6+
perform_service(param: 'exception')
7+
end
8+
assert_match(/incorrect param/i, error.message)
9+
```
10+
11+
you can now write this
12+
```ruby
13+
assert_raises(ArgumentError, match: /incorrect param/i) do
14+
perform_service(param: 'exception')
15+
end
16+
```
17+
18+
*fatkodima*
19+
120
* Add `Rails.env.local?` shorthand for `Rails.env.development? || Rails.env.test?`.
221

322
*DHH*

activesupport/lib/active_support/testing/assertions.rb

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,19 @@ def assert_not(object, message = nil)
2323
assert !object, message
2424
end
2525

26+
# Asserts that a block raises one of <tt>exp</tt>. This is an enhancement of the
27+
# standard Minitest assertion method with the ability to test error messages.
28+
#
29+
# assert_raises(ArgumentError, match: /incorrect param/i) do
30+
# perform_service(param: 'exception')
31+
# end
32+
#
33+
def assert_raises(*exp, match: nil, &block)
34+
error = super(*exp, &block)
35+
assert_match(match, error.message) if match
36+
error
37+
end
38+
2639
# Assertion that the block should not raise an exception.
2740
#
2841
# Passes if evaluated code in the yielded block raises no exception.

activesupport/test/test_case_test.rb

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,20 @@ def test_assert_not
2828
assert_equal "custom", e.message
2929
end
3030

31+
def test_assert_raises_with_match_pass
32+
assert_raises(ArgumentError, match: /incorrect/i) do
33+
raise ArgumentError, "Incorrect argument"
34+
end
35+
end
36+
37+
def test_assert_raises_with_match_fail
38+
assert_raises(Minitest::Assertion, match: "Expected /incorrect/i to match \"Wrong argument\".") do
39+
assert_raises(ArgumentError, match: /incorrect/i) do
40+
raise ArgumentError, "Wrong argument"
41+
end
42+
end
43+
end
44+
3145
def test_assert_no_difference_pass
3246
assert_no_difference "@object.num" do
3347
# ...

0 commit comments

Comments
 (0)