RSpec参数匹配哈希数组

时间:2014-10-28 15:36:58

标签: ruby rspec rspec3

我想使用rspec提供的参数匹配器来匹配哈希数组。这是我想要的代码:

  context 'logging stock levels' do
    subject { double(:stock_logger, stock_updated: nil) }
    let(:stock_importer) { described_class.new(logger: subject) }
    before(:each) { stock_importer.import }

    it { is_expected.to have_received(:stock_updated)
                          .with(array_including(hash_including('sku', 'count_on_hand'))) }
  end

这个错误与我的参数不匹配。我能想出的唯一可行解决方案如下:

  context 'logging stock levels' do
    subject { double(:stock_logger, stock_updated: nil) }
    let(:stock_importer) { described_class.new(logger: subject) }
    before(:each) { stock_importer.import }

    it do
      is_expected.to have_received(:stock_updated) do |stock_levels|
        expect(stock_levels).to include(include('sku', 'count_on_hand'))
      end
    end
  end

我做错了什么?

2 个答案:

答案 0 :(得分:0)

尝试使用哈希键array_including。未经测试,但也许是这样的:

it do
  is_expected.to have_received(:stock_updated)
    .with(include(include("sku"), include("bar")))
end

答案 1 :(得分:0)

使用Rspec 3.3,这对我有用:

expect(<Object>).to receive(:method).with(
  array_including(hash_including( {"id" => some_id} ))
)