【问题标题】:RSpec expect to receive method with array but order does not matterRSpec 期望接收带有数组的方法,但顺序无关紧要
【发布时间】:2016-02-07 14:01:51
【问题描述】:

假设我有方法#sum,它接受一个数组并计算所有元素的总和。我把它存根了:

  before do
    expect(calculation_service).to receive(:sum?).with([1, 2, 3]) { 6 }
  end

不幸的是,我的测试服以随机顺序通过数组。因为这个错误被提出:

 Failure/Error: subject { do_crazy_stuff! }
   #<InstanceDouble() (CalculationService)> received :sum? with unexpected arguments
     expected: ([1, 2, 3])
          got: ([3, 2, 1])

是否可以存根方法调用忽略数组元素的顺序? array_including(1, 2, 3) 不保证数组大小,所以这里可能不是最好的解决方案

【问题讨论】:

    标签: ruby-on-rails arrays ruby ruby-on-rails-4 rspec


    【解决方案1】:

    您可以将任何 RSpec 匹配器传递给 with,而 contain_exactly(1, 2, 3) 完全符合您的要求,因此您可以将其传递给:

    expect(calculation_service).to receive(:sum?).with(contain_exactly(1, 2, 3)) { 6 }
    

    但是,“恰好包含 1、2、3”读起来不太好(并且失败消息在语法上也同样尴尬),因此 RSpec 3 提供了解决这两个问题的别名。在这种情况下,您可以使用a_collection_containing_exactly

    expect(calculation_service).to receive(:sum?).with(
      a_collection_containing_exactly(1, 2, 3)
    ) { 6 }
    

    【讨论】:

    • 如果您将数组传递给 contains_exactly,请记住传播数组,例如 expect(calculation_service).to receive(:sum?).with(contain_exactly(*my_array))
    【解决方案2】:

    您也可以使用方法match_array。这样,您不需要先拆分数组的元素;相反,您可以只使用整个数组来匹配。

    所以你可以使用:

    expect(calculation_service).to receive(:sum?).with(match_array([1, 2, 3])) { 6 }
    

    【讨论】:

      猜你喜欢
      • 2016-05-23
      • 1970-01-01
      • 1970-01-01
      • 2015-06-28
      • 1970-01-01
      • 2018-12-07
      • 2018-05-19
      • 1970-01-01
      • 2017-07-28
      相关资源
      最近更新 更多