毎回調べているのでいい加減整理しておきたい。

サマリ

先に結果を書いておく。

  • 配列の要素が一致し、かつ、並び順は問わない: contain_exactly
    • match_arrayでも同じ
  • 配列の要素が一致し、かつ、並び順も一致する: eq
  • 配列の要素が部分的に一致する: include

contain_exactly / match_array

配列の要素が一致し、かつ、並び順は問わない

1
2
3
4
5
6
7
8
9
RSpec.describe [1, 2, 3] do
  it '' do
    is_expected.to contain_exactly(1, 2, 3)
    is_expected.to contain_exactly(3, 2, 1)
    is_expected.not_to contain_exactly(1)

    is_expected.to match_array([3, 2, 1])
  end
end

eq

配列の要素が一致し、かつ、並び順も一致する

1
2
3
4
5
6
RSpec.describe [1, 2, 3] do
  it '' do
    is_expected.to eq([1, 2, 3])
    is_expected.not_to eq([3, 2, 1])
  end
end

include

配列の要素が部分的に一致する

1
2
3
4
5
6
RSpec.describe [ 1, 2, 3 ] do
  it '' do
    is_expected.to include(1, 2)
    is_expected.not_to include(4)
  end
end

(おまけ)start_with / end_with

配列の先頭/末尾の要素が一致する

1
2
3
4
5
6
7
8
9
RSpec.describe [ 1, 2, 3 ] do
  it '' do
    is_expected.to start_with(1, 2)
    is_expected.not_to start_with(2, 3)
    is_expected.to end_with(2, 3)
    is_expected.to end_with(3)
    is_expected.not_to end_with(1, 2)
  end
end