寻找一个rspec匹配器来检查要包含在数组中的值(Looking for a rspec matcher that checks a value to be included in array)

编程入门 行业动态 更新时间:2024-10-26 15:19:53
寻找一个rspec匹配器来检查要包含在数组中的值(Looking for a rspec matcher that checks a value to be included in array)

我怎么写这个:

给定一个数组b = ['one', 'two', 'three']

我期望值a包含在数组b 。

我想将它与all匹配器一起使用,以便我的最终代码如下所示:

b = ['one', 'two', 'three'] my_list = [ {'type' => 'one'}, {'type' => 'two'}, {'type' => 'three'} ] expect(my_list).to all(include("type" => a_value_included_in(b))

正在测试的是:

my_list所有哈希都必须有一个type键,其值在数组b 。

Rspec中有这样的内置匹配器吗?

而且,除了使用明显的反转外,如何检查数组中是否包含值: expect([1, 2, 3]).to include(value) ,在我的示例中,它并不适合?

How can I write this:

Given an array b = ['one', 'two', 'three']

I expect value a to be included in the array b.

I want to use it together with an all matcher so my final code would look like this:

b = ['one', 'two', 'three'] my_list = [ {'type' => 'one'}, {'type' => 'two'}, {'type' => 'three'} ] expect(my_list).to all(include("type" => a_value_included_in(b))

Which is testing for:

all hashes from my_list must have a type key whose value is in array b.

Is there such built-in matcher in Rspec?

And how do you check inclusion of a value in the array besides using the obvious reverse: expect([1, 2, 3]).to include(value), which in my example, is not really fitting in?

最满意答案

如果你想检查b 每个字符串是否存在于my_list任何哈希中:

b = ['one', 'two', 'three'] my_list = [ {'type' => 'one'}, {'type' => 'two'}, {'type' => 'three'} ] b.each do |str| expect(my_list.find { |h| h['type'] == str }).to be_present end

或者,您可以与:

expect(my_list.map { |h| h['type'] }.sort) to eq(b.sort)

所以当有人添加my_list << { 'type' => 'not_in_list' } ,规范将失败。

expect(my_list.map { |h| b.include?(h['type']) }.uniq).to eq(true)

If you want to check if every string from b is present in any of the hashes from my_list:

b = ['one', 'two', 'three'] my_list = [ {'type' => 'one'}, {'type' => 'two'}, {'type' => 'three'} ] b.each do |str| expect(my_list.find { |h| h['type'] == str }).to be_present end

Or, you can go with:

expect(my_list.map { |h| h['type'] }.sort) to eq(b.sort)

So when someone adds my_list << { 'type' => 'not_in_list' } the spec will fail.

expect(my_list.map { |h| b.include?(h['type']) }.uniq).to eq(true)

更多推荐

本文发布于:2023-07-18 11:40:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1159811.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组中   matcher   rspec   array   included

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!