【问题标题】:how to check expected result matches any of give values in rspec?如何检查预期结果是否匹配 rspec 中的任何给定值?
【发布时间】:2025-12-09 03:55:01
【问题描述】:

我们如何断言与[1, 3, 5, 6, 10] 中的任何一个匹配的值?

我看起来像matches_any_of([1, 3, 5, 6, 10])

【问题讨论】:

    标签: ruby-on-rails ruby rspec tdd


    【解决方案1】:

    你可以这样做:

    describe 'thing' do
      it 'includes' do
        expect([1,3,5,6,10]).to include(3) #or your resulting variable
      end
    end
    

    在回答您的评论时,您可以编写自定义匹配器,或者您可以执行以下操作:

    describe 'thing' do
      it 'includes' do
        i = 3
        results = [1,3,5,6,10].keep_if { |el| el == i }
        expect(results).to_not be_empty
      end
    end
    

    【讨论】:

    • 其实我想要其他方式,比如expect(1).to matches_any_of([1,3,5,6,10])
    【解决方案2】:

    我想你正在寻找RSpec's built-in include matcher:

    expect([1, 3, 5, 6, 10]).to include(a)
    

    【讨论】:

      【解决方案3】:

      我是这样破解的

      expect([1, 3, 5, 6, 10].include?(result).to be_truthy

      【讨论】: