Skip to content

Commit 26db4c5

Browse files
committed
Add Assert Two Arrays Have The Same Items With RSpec as a rails til
1 parent c1db2af commit 26db4c5

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ and pairing with smart people at Hashrocket.
99

1010
For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud).
1111

12-
_884 TILs and counting..._
12+
_885 TILs and counting..._
1313

1414
---
1515

@@ -509,6 +509,7 @@ _884 TILs and counting..._
509509
- [ActiveRecord Query For This Or That](rails/active-record-query-for-this-or-that.md)
510510
- [Advance The Date](rails/advance-the-date.md)
511511
- [All or Nothing Database Transactions](rails/all-or-nothing-database-transactions.md)
512+
- [Assert Two Arrays Have The Same Items With RSpec](rails/assert-two-arrays-have-the-same-items-with-rspec.md)
512513
- [Attach A File With Capybara](rails/attach-a-file-with-capybara.md)
513514
- [Attribute Getter without the Recursion](rails/attribute-getter-without-the-recursion.md)
514515
- [Attribute Was](rails/attribute-was.md)
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# Assert Two Arrays Have The Same Items With RSpec
2+
3+
Methods that return arrays of values with inconsistent orderings can be
4+
annoying to test with the `#eq` matcher. To keep your test from fickering,
5+
you'd have to ensure the comparison is the same every time.
6+
7+
```ruby
8+
it "has the correct values" do
9+
expect(fetch_colors(params).sort).to eq(["blue", "green", "yellow"])
10+
end
11+
```
12+
13+
It'd be better if we could keep our test focused and simple. If sort order
14+
isn't something we care about, then it shouldn't be part of our test. RSpec has
15+
a matcher for this kind of scenario --
16+
[`#match_array`](https://www.rubydoc.info/github/rspec/rspec-expectations/RSpec%2FMatchers:match_array).
17+
18+
```ruby
19+
it "has the correct values" do
20+
expect(fetch_colors(params)).to match_array(["blue", "green", "yellow"])
21+
end
22+
```
23+
24+
This allows us to ensure that each side of the comparison has the same set
25+
values, irrespective of ordering.

0 commit comments

Comments
 (0)