【问题标题】:How rspec array should include? another arrayrspec 数组应该如何包含?另一个数组
【发布时间】:2013-01-08 11:31:52
【问题描述】:

我正在尝试测试一个数组是否包含另一个(rspec 2.11.0)

test_arr = [1, 3]

describe [1, 3, 7] do
  it { should include(1,3) }
  it { should eval("include(#{test_arr.join(',')})")}
  #failing
  it { should include(test_arr) }
end    

这是结果 rspec 规范/test.spec ..F

Failures:

  1) 1 3 7 
     Failure/Error: it { should include(test_arr) }
       expected [1, 3, 7] to include [1, 3]
     # ./spec/test.spec:7:in `block (2 levels) in <top (required)>'

Finished in 0.00125 seconds
3 examples, 1 failure

Failed examples:

rspec ./spec/test.spec:7 # 1 3 7 

include rspec 方法不接受数组参数,有更好的方法来避免“eval”吗?

【问题讨论】:

    标签: arrays testing rspec


    【解决方案1】:

    只需使用splat (*) 运算符,它将元素数组扩展为可传递给方法的参数列表:

    test_arr = [1, 3]
    
    describe [1, 3, 7] do
      it { should include(*test_arr) }
    end
    

    【讨论】:

    • 天啊!这令人兴奋……说真的,这在规范中真的很有用,我不知道#include 支持的参数列表。谢谢!
    【解决方案2】:

    如果你想断言子集数组的 order,你需要做的比 should include(..) 多一点,因为 RSpec 的 include 匹配器只断言每个元素显示在数组中的任何位置,并不是所有的参数都按顺序显示。

    我最终使用each_cons 来验证子数组是否按顺序存在,如下所示:

    describe [1, 3, 5, 7] do
      it 'includes [3,5] in order' do
        subject.each_cons(2).should include([3,5])
      end
    
      it 'does not include [3,1]' do
        subject.each_cons(2).should_not include([3,1])
      end
    end
    

    【讨论】:

    • 老实说,这太棒了。让我检查一下我需要什么。
    猜你喜欢
    • 2019-09-03
    • 2013-05-06
    • 2017-05-30
    • 1970-01-01
    • 2020-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多