Rspec : is there a matcher to match array of arrays, not testing order

Viewed 5776

I try to test if two arrays of arrays contain same elements, without testing order of elements. (Rails 5.2 / Rspec-rails 3.8.2)

exemple :

[['a1', 'a2'], ['b1', 'b2']]
[['b2', 'b1'], ['a2', 'a1']]

I tried with match_array and with contain_exactly but this works only for the first level of my array.


  tab1 = [['a1', 'a2'], ['b1', 'b2']]
  tab2 = [['b1', 'b2'], ['a1', 'a2']]
  tab3 = [['a2', 'a1'], ['b2', 'b1']]
  tab4 = [['b2', 'b1'], ['a2', 'a1']]

  expect(tab1).to match_array tab2  # true
  expect(tab1).to match_array tab3  # false
  expect(tab1).to match_array tab4  # false

Is there a matcher to do this ? Or maybe a simple way with composable matchers ? Thanks

EDIT The solution I find is to do :

expect(tab1).to contain_exactly(contain_exactly('a1', 'a2'),
                                contain_exactly('b1', 'b2'))

but I would like to find something like this

expect(tab1).to ....... tab2
3 Answers

There are two simple ways to achieve

 describe 'two array with random order' do

    it 'arrays are equals if content is same' do

      tab1 = [['a1', 'a2'], ['b1', 'b2']]
      tab2 = [['b1', 'b2'], ['a1', 'a2']]
      tab3 = [['a2', 'a1'], ['b2', 'b1']]
      tab4 = [['b2', 'b1'], ['a2', 'a1']]

      #option 1
      expect(tab1.sort).to match_array tab2.sort
      expect(tab1.sort).not_to match_array tab3.sort
      expect(tab1.map(&:sort).sort).to match_array tab3.map(&:sort).sort
      expect(tab1.sort).not_to match_array tab4.sort

      # Option 2
      expect(tab1).to include *tab2
      expect(tab1).not_to include *tab3
      expect(tab1.map(&:sort)).to include *tab3.map(&:sort)
      expect(tab1).not_to include *tab4
    end
  end

I think I found a solution. Thanks to comment if you think that it does not always work.

it 'checks that arrays contain the same elements (do not check order)' do
  tab1 = [['a1', 'a2'], ['b1', 'b2']]
  tab4 = [['b2', 'b1'], ['a2', 'a1']]
  expect(tab1.map(&:sort)).to match_array(tab4.map(&:sort))
end
Related