Rspec匹配哈希数组

Pez*_*lio 19 ruby arrays hash rspec

我有一个哈希数组,为了论证的缘故,这样:

[{"foo"=>"1", "bar"=>"1"}, {"foo"=>"2", "bar"=>"2"}]
Run Code Online (Sandbox Code Playgroud)

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

[{"foo" => "1", "bar" => "2"}, {"foo" => "2", "bar" => "2"}].should include("foo" => "2"))
Run Code Online (Sandbox Code Playgroud)

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

Kho*_*yen 33

怎么样?

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

  • 这有效,但我会将其表达为:`expect(hashes).to include(a_hash_including("foo"=>"2"))` (8认同)

hji*_*ing 8

您可以使用该any?方法.见对于文档.

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


Fer*_*ida 5

您可以使用可组合匹配器

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
Run Code Online (Sandbox Code Playgroud)

并在这样的规格中使用它

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
Run Code Online (Sandbox Code Playgroud)


ilg*_*gam 5

使用可组合的匹配器

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