all
匹配器
使用 all
匹配器来指定集合中的所有对象都通过期望的匹配器。 这适用于任何可枚举对象。
expect([1, 3, 5]).to all( be_odd )
expect([1, 3, 5]).to all( be_an(Integer) )
expect([1, 3, 5]).to all( be < 10 )
expect([1, 3, 4]).to all( be_odd ) # fails
匹配器还支持复合匹配器
expect([1, 3, 5]).to all( be_odd.and be < 10 )
expect([1, 4, 21]).to all( be_odd.or be < 10 )
如果您正在寻找集合中通过期望的“任何”成员,请查看 include
匹配器。
数组用法
给定一个名为“array_all_matcher_spec.rb”的文件,其中包含
RSpec.describe [1, 3, 5] do
it { is_expected.to all( be_odd ) }
it { is_expected.to all( be_an(Integer) ) }
it { is_expected.to all( be < 10 ) }
# deliberate failures
it { is_expected.to all( be_even ) }
it { is_expected.to all( be_a(String) ) }
it { is_expected.to all( be > 2 ) }
end
当我运行 rspec array_all_matcher_spec.rb
时
那么输出应该包含所有这些
6 个示例,3 个失败 |
预计 [1, 3, 5] 全部是偶数 |
预计 [1, 3, 5] 全部是 String 类型 |
预计 [1, 3, 5] 全部大于 2 |
复合匹配器用法
给定一个名为“compound_all_matcher_spec.rb”的文件,其中包含
RSpec.describe ['anything', 'everything', 'something'] do
it { is_expected.to all( be_a(String).and include("thing") ) }
it { is_expected.to all( be_a(String).and end_with("g") ) }
it { is_expected.to all( start_with("s").or include("y") ) }
# deliberate failures
it { is_expected.to all( include("foo").and include("bar") ) }
it { is_expected.to all( be_a(String).and start_with("a") ) }
it { is_expected.to all( start_with("a").or include("z") ) }
end
当我运行 rspec compound_all_matcher_spec.rb
时
那么输出应该包含所有这些
6 个示例,3 个失败 |
预计 [“anything”, “everything”, “something”] 全部包含 “foo” 并且包含 “bar” |
预计 [“anything”, “everything”, “something”] 全部是 String 类型并且以 “a” 开头 |
预计 [“anything”, “everything”, “something”] 全部以 “a” 开头或包含 “z” |