Rspec: "array.should = = another array " but without concern for order
A menudo quiero comparar matrices y asegurarme de que contienen los mismos elementos, en cualquier orden. ¿Hay una manera concisa de hacer esto en RSpec?
Aquí hay métodos que no son aceptables:
#to_set
Por ejemplo:
array.to_set.should == another_array.to_set
Esto falla cuando los arrays contienen elementos duplicados.
#sort
Por ejemplo:
array.sort.should == another_array.sort
Esto falla cuando los elementos arrays no implementan #<=>
4 answers
Intenta array.should =~ another_array
La mejor documentación sobre esto que puedo encontrar es el código en sí, que es aquí.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-06-05 03:08:52
Desde RSpec 2.11 también puedes usar match_array
.
array.should match_array(another_array)
Que podría ser más legible en algunos casos.
[1, 2, 3].should =~ [2, 3, 1]
# vs
[1, 2, 3].should match_array([2, 3, 1])
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-08-04 20:13:20
He encontrado que =~
es impredecible y ha fallado sin razón aparente. Pasado 2.14, probablemente debería usar
expect([1, 2, 3]).to match_array([2, 3, 1])
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-17 20:36:38
No está muy bien documentado, pero he añadido enlaces de todos modos:
Rspec3 docs
expect(actual).to eq(expected)
Rspec2 docs
expect([1, 2, 3]).to match_array([2, 3, 1])
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-03-28 19:42:38