"Array.should = = another array " ale bez troski o porządek

Często chcę porównać tablice i upewnić się, że zawierają te same elementy, w dowolnej kolejności. Czy jest jakiś zwięzły sposób, aby to zrobić w RSpec?

Oto metody, które nie są akceptowalne:

#to_set

Na przykład:

array.to_set.should == another_array.to_set

To nie powiedzie się, gdy tablice zawierają zduplikowane elementy.

#sort

Na przykład:

array.sort.should == another_array.sort

To nie powiedzie się, gdy elementy tablic nie implementują #<=>

Author: Freedom_Ben, 2010-06-05

4 answers

Try array.should =~ another_array

Najlepszą dokumentacją na ten temat jest sam kod, który jest tutaj .

 259
Author: x1a4,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-06-05 03:08:52

Od RSpec 2.11 można również używać match_array.

array.should match_array(another_array)

Które w niektórych przypadkach mogłyby być bardziej czytelne.

[1, 2, 3].should =~ [2, 3, 1]
# vs
[1, 2, 3].should match_array([2, 3, 1])
 215
Author: Valentin Nemcev,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-08-04 20:13:20

Uznałem =~ za nieprzewidywalny i zawiodłem bez wyraźnego powodu. Po 2.14 powinieneś prawdopodobnie użyć

expect([1, 2, 3]).to match_array([2, 3, 1])
 123
Author: Josh Kovach,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-10-17 20:36:38

Niezbyt dobrze udokumentowane, ale i tak dodałem linki:

Rspec3 docs

expect(actual).to eq(expected)


Rspec2 docs

expect([1, 2, 3]).to match_array([2, 3, 1])

 0
Author: Blair Anderson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-03-28 19:42:38