【问题标题】:Composing matchers in Rspec在 Rspec 中编写匹配器
【发布时间】:2018-09-25 21:29:10
【问题描述】:

Rspec 支持组合匹配器。它提供的组成匹配器列表是这样的:

all(matcher)
include(matcher, matcher)
start_with(matcher)
end_with(matcher)
contain_exactly(matcher, matcher, matcher)
match(matcher)
change {}.from(matcher).to(matcher)
change {}.by(matcher)

所有组合匹配器非常直观。您可以将匹配器传递给组合匹配器,并且传递的匹配器必须返回 true 才能使期望为 true:

expect(@items).to all(be_visible & be_in_stock)

但我不确定 start_with 和 end_with 组成匹配器。看这个例子:

fruits = ['apple', 'banana', 'cherry']
expect(fruits).to start_with( start_with('a') )

在这个例子中,外层和内层 start_with 做了什么?

【问题讨论】:

    标签: ruby rspec


    【解决方案1】:

    在您的示例中,您正在测试fruits 的第一个元素是否以字符a 开头。因此,外部starts_with 定位数组的第一个元素,内部starts_with 定位第一个元素的开头。

    您的示例通过,但例如失败:

    fruits = ['banana', 'apple', 'cherry']
    expect(fruits).to start_with( start_with('a') )
    

    rspec-expectations tests 的数组中有几个示例,您希望测试第一个元素是否以给定值或字符串开头或结尾。例如:

    expect([1.01, "food", 3]).to start_with(a_value_within(0.2).of(1), a_string_matching(/foo/))
    
    expect([3, "food", 1.1]).to end_with(a_value_within(0.2).of(1))
    

    还相关:RSpec starts_with matcher variant using regular expressions

    【讨论】:

    • 所以外层的starts_with指向数组的第一个元素,而内层的starts_with指向第一个元素的第一个字符。
    • 没错!我也会将其添加到答案中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多