1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-03 07:08:01 +00:00

Add Avoid Double Negation With Minitest Refute as a Ruby TIL

This commit is contained in:
jbranchaud
2025-09-16 09:33:48 -05:00
parent 2b5df03981
commit 8613c21f41
2 changed files with 41 additions and 1 deletions

View File

@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186).
_1655 TILs and counting..._
_1656 TILs and counting..._
See some of the other learning resources I work on:
- [Get Started with Vimium](https://egghead.io/courses/get-started-with-vimium~3t5f7)
@@ -1295,6 +1295,7 @@ If you've learned something here, support my efforts writing daily TILs by
- [Assert About An Object's Attributes With RSpec](ruby/assert-about-an-objects-attributes-with-rspec.md)
- [Assoc For Hashes](ruby/assoc-for-hashes.md)
- [Audit Your Ruby Project For Any CVEs](ruby/audit-your-ruby-project-for-any-cves.md)
- [Avoid Double Negation With Minitest Refute](ruby/avoid-double-negation-with-minitest-refute.md)
- [Block Comments](ruby/block-comments.md)
- [Block Syntaxes Have Different Precedence](ruby/block-syntaxes-have-different-precedence.md)
- [Build HTTP And HTTPS URLs](ruby/build-http-and-https-urls.md)

View File

@@ -0,0 +1,39 @@
# Avoid Double Negation With Minitest Refute
As I'm writing some tests for a recent feature, I end up with various test
cases that make a variety of assertions.
```ruby
assert_equal resp_body["id"], expected_id
# ...
assert_not resp_body["items"].empty?
```
The first assertion reads pretty naturally. The second one requires some extra
mental parsing because of the `_not` and then the "negative" check of
`#empty?`.
Another way to express this that might read more naturally is with
[`#refute`](https://ruby-doc.org/stdlib-3.0.2/libdoc/minitest/rdoc/Minitest/Assertions.html#method-i-refute).
```ruby
refute resp_body["items"].empty?
```
This says that we _refute_ that items is empty, so the assertion should fail if
empty.
Ruby is flexible in other ways. We may also prefer to write it as:
```ruby
assert resp_body["items"].present?
```
Or we could even take advantage of a more specific variant of refute with
[`#refute_empty`](https://ruby-doc.org/stdlib-3.0.2/libdoc/minitest/rdoc/Minitest/Assertions.html#method-i-refute_empty):
```ruby
refute_empty resp_body["items"]
```