From 26db4c5c0772535d92b1c606770fc253c6221dd0 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Wed, 4 Dec 2019 17:28:18 -0600 Subject: [PATCH] Add Assert Two Arrays Have The Same Items With RSpec as a rails til --- README.md | 3 ++- ...o-arrays-have-the-same-items-with-rspec.md | 25 +++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) create mode 100644 rails/assert-two-arrays-have-the-same-items-with-rspec.md diff --git a/README.md b/README.md index 75d1dd4..76b4499 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ and pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud). -_884 TILs and counting..._ +_885 TILs and counting..._ --- @@ -509,6 +509,7 @@ _884 TILs and counting..._ - [ActiveRecord Query For This Or That](rails/active-record-query-for-this-or-that.md) - [Advance The Date](rails/advance-the-date.md) - [All or Nothing Database Transactions](rails/all-or-nothing-database-transactions.md) +- [Assert Two Arrays Have The Same Items With RSpec](rails/assert-two-arrays-have-the-same-items-with-rspec.md) - [Attach A File With Capybara](rails/attach-a-file-with-capybara.md) - [Attribute Getter without the Recursion](rails/attribute-getter-without-the-recursion.md) - [Attribute Was](rails/attribute-was.md) diff --git a/rails/assert-two-arrays-have-the-same-items-with-rspec.md b/rails/assert-two-arrays-have-the-same-items-with-rspec.md new file mode 100644 index 0000000..5d2b37a --- /dev/null +++ b/rails/assert-two-arrays-have-the-same-items-with-rspec.md @@ -0,0 +1,25 @@ +# Assert Two Arrays Have The Same Items With RSpec + +Methods that return arrays of values with inconsistent orderings can be +annoying to test with the `#eq` matcher. To keep your test from fickering, +you'd have to ensure the comparison is the same every time. + +```ruby +it "has the correct values" do + expect(fetch_colors(params).sort).to eq(["blue", "green", "yellow"]) +end +``` + +It'd be better if we could keep our test focused and simple. If sort order +isn't something we care about, then it shouldn't be part of our test. RSpec has +a matcher for this kind of scenario -- +[`#match_array`](https://www.rubydoc.info/github/rspec/rspec-expectations/RSpec%2FMatchers:match_array). + +```ruby +it "has the correct values" do + expect(fetch_colors(params)).to match_array(["blue", "green", "yellow"]) +end +``` + +This allows us to ensure that each side of the comparison has the same set +values, irrespective of ordering.