【问题标题】:RSpec argument match array of hashesRSpec 参数匹配哈希数组
【发布时间】:2014-10-28 15:36:58
【问题描述】:

我想使用 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

我是不是做错了什么?

【问题讨论】:

    标签: ruby rspec rspec3


    【解决方案1】:

    使用 Rspec 3.3,这对我有用:

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

    【讨论】:

      【解决方案2】:

      尝试array_including,但使用哈希键。未经测试,但可能类似于:

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

      【讨论】:

      • 我试过array_including('sku' =&gt; a_kind_of(String), 'count_on_hand' =&gt; a_kind_of(String))),但不匹配。如果它仍然有效,那就没有意义了。
      • expect([{:foo =&gt; "blah", :bar =&gt; "blah2"}]).to include(:foo =&gt; be_a_kind_of(String), :bar =&gt; be_a_kind_of(String)) 刚刚在控制台中为我工作
      • 是的,这就是我目前解决的方法。但是,我想使用 rspec-mocks 中的 arg 匹配器语法来解决它。
      • 我只是不明白为什么array_including(hash_including('sku', 'count_on_hand')) 不工作而hash_including(data: hash_including('a', 'b')) 工作。
      • 哦,我想我明白了,这行得通:expect([{:foo =&gt; "blah", :bar =&gt; "blah2"}]).to include(include(:foo), include(:bar)) 也许不指定数组/哈希会有所帮助?我修改答案给你试试
      猜你喜欢
      • 2014-07-12
      • 2018-06-14
      • 1970-01-01
      • 1970-01-01
      • 2014-08-26
      • 1970-01-01
      • 2021-11-18
      • 2020-07-16
      • 2021-04-23
      相关资源
      最近更新 更多