Rspec - Check if an array have same elements than other, regardless of the order
rspec, ruby, ruby-on-rails, ruby-on-rails-2
Solution
Here was my wrong matcher (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 builtin matcher, best solution
use `Set`:
Something like:
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
Problem
I'm not sure if its a Rspec question, but I only encountred this problem on Rspec tests. I want to check if an array is equal to another array, regardless of the elements order : ``` [:b, :a, :c] =?= [:a, :b, :c] ``` My current version : ``` my_array.length.should == 3 my_array.should include(:a) my_array.should include(:b) my_array.should include(:c) ``` Is there any method on Rspec, ruby or Rails for do something like this : ``` my_array.should have_same_elements_than([:a, :b, :c]) ``` Regards