diff --git a/README.md b/README.md index af46242..81d11e7 100644 --- a/README.md +++ b/README.md @@ -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) diff --git a/ruby/avoid-double-negation-with-minitest-refute.md b/ruby/avoid-double-negation-with-minitest-refute.md new file mode 100644 index 0000000..e4a523f --- /dev/null +++ b/ruby/avoid-double-negation-with-minitest-refute.md @@ -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"] +```