Rspec匹配哈希数组

时间:2014-05-22 19:53:46

标签: ruby arrays hash rspec

我有一个哈希数组,为了论证起见,这样:

[{"foo"=>"1", "bar"=>"1"}, {"foo"=>"2", "bar"=>"2"}]

使用Rspec,我想测试数组中是否存在"foo" => "2",但我不在乎它是第一项还是第二项。我试过了:

[{"foo" => "1", "bar" => "2"}, {"foo" => "2", "bar" => "2"}].should include("foo" => "2"))

但这并不起作用,因为哈希应该完全匹配。有没有办法部分测试每个哈希的内容?

5 个答案:

答案 0 :(得分:29)

怎么样?

hashes = [{"foo" => "1", "bar" => "2"}, {"foo" => "2", "bar" => "2"}]
expect(hashes).to include(include('foo' => '2'))

答案 1 :(得分:7)

您可以使用any?方法。有关文档,请参阅this

hashes = [{"foo" => "1", "bar" => "2"}, {"foo" => "2", "bar" => "2"}]
expect(hashes.any? { |hash| hash['foo'] == '2' }).to be_true

答案 2 :(得分:2)

您可以使用可组合匹配器

http://rspec.info/blog/2014/01/new-in-rspec-3-composable-matchers/

但我更喜欢定义像这样的自定义匹配器

require 'rspec/expectations'

RSpec::Matchers.define :include_hash_matching do |expected|
  match do |array_of_hashes|
    array_of_hashes.any? { |element| element.slice(*expected.keys) == expected }
  end
end

并在像这样的规范中使用它

describe RSpec::Matchers do
  describe '#include_hash_matching' do
    subject(:array_of_hashes) do
      [
        {
          'foo' => '1',
          'bar' => '2'
        }, {
          'foo' => '2',
          'bar' => '2'
        }
      ]
    end

    it { is_expected.to include_hash_matching('foo' => '1') }

    it { is_expected.to include_hash_matching('foo' => '2') }

    it { is_expected.to include_hash_matching('bar' => '2') }

    it { is_expected.not_to include_hash_matching('bar' => '1') }

    it { is_expected.to include_hash_matching('foo' => '1', 'bar' => '2') }

    it { is_expected.not_to include_hash_matching('foo' => '1', 'bar' => '1') }

    it 'ignores the order of the keys' do
      is_expected.to include_hash_matching('bar' => '2', 'foo' => '1')
    end
  end
end


Finished in 0.05894 seconds
7 examples, 0 failures

答案 3 :(得分:2)

使用Composable Matchers

hashes = [{"foo" => "1", "bar" => "2"}, {"foo" => "2", "bar" => "2"}]
expect(hashes).to match([a_hash_including('foo' => '2'), a_hash_including('foo' => '1')])

答案 4 :(得分:0)

如果哈希的单独测试不是严格的要求,我会这样做:

[{"foo" => "1", "bar" => "2"}, {"foo" => "2", "bar" => "2"}].map{ |d| d["foo"] }.should include("2")