Rspec - check if the array has the same elements as the others, regardless of order

I am not sure if this is an Rspec question, but I only ran into this problem when checking Rspec.

I want to check if an array is equal to another array, regardless of the order of the elements:

[:b, :a, :c] =?= [:a, :b, :c] 

My current version is:

 my_array.length.should == 3 my_array.should include(:a) my_array.should include(:b) my_array.should include(:c) 

Is there any method for Rspec, ruby, or Rails to do the following:

 my_array.should have_same_elements_than([:a, :b, :c]) 

Hello

+4
source share
5 answers

Here was my wrong match (thanks @steenslag):

 RSpec::Matchers.define :be_same_array_as do |expected_array| match do |actual_array| (actual_array | expected_array) - (actual_array & expected_array) == [] end end 

Other solutions:

  • use the built-in socket, the best solution

  • use Set :

Sort of:

 require 'set' RSpec::Matchers.define :be_same_array_as do |expected_array| match do |actual_array| Set.new(actual_array) == Set.new(expected_array) end end 
+3
source

You can use the operator =~ :

 [:b, :a, :c].should =~ [:a, :b, :c] # pass 

From docs :

Passes if the actual contains everything expected, regardless of order. This works for collections. Go into multiple arguments, and this will only be if all arguments are found in the collection.

For RSpec, expect the syntax there match_array :

 expect([:b, :a, :c]).to match_array([:a, :b, :c]) # pass 

or contain_exactly if you pass individual elements:

 expect([:b, :a, :c]).to contain_exactly(:a, :b, :c) # pass 
+12
source

That should work.

 [:b, :a, :c].sort == [:a, :b, :c].sort 
+3
source

I think all the answers seem pretty old. Last matches contain_exactly .

You can just do -

 expect([:b, :a, :c]).to contain_exactly(:a, :b, :c) 

Please, not that in contain_exactly we do not pass the whole array, but pass separate elements.

Ref - Rspec Manual

0
source

All Articles