https://relishapp.com/rspec/rspec-expectations/v/3-7/docs
RSpec.info/documentation/
be_completed是Predicate matchers
expect(actual).to be_xxx #passes if actual.xxx?
RSpec::Expectations lets you express expected outcomes on an object in an example.
Built-in matchers
expect(actual_value).to eq(expected_value)
expect(actual_value).to be >= expected_value 包括>, < , <=, >=
expect(actual_value).to match(/expression/) 正则表达式(expect不支持匹配符号 =~)
expect(array).to all(inner_matcher) #让array通过inner_matcher
如:expect([1,2,3]).to all(be_truthy)
expect(array).to contain_exactly(expected_array) #如果实际的和期待的数组包含相同的元素,则期待成功。不考虑顺序。
contain_exactly等同于match_array
expect(actual).to exist
Collection membership
expect(actual).to include(expected) #actual可以是数组,字符串,hash.
例子:expect([1,2,3]).to include(1,2), expect({:a => "b"}).to include(:a => "b")
include的变型, start_with, end_with
Types/classes
expect(actual).to be_an_instance_of(expected)
# passes if actual.class == expected
expect(actual).to be_a(expected) #passes if actual.kind_of?(expected)
Predicate matchers
expect(actual).to be_xxx #passes if actual.xxx?
expect(actual).to have_xxx(:arg) #passes if actual.has_xxx?(:arg)
expect(actual).to have_attributes(key/value pairs)
Truthiness
expect(actual).to be_truthy/falsy # passes if actual is truthy (not nil or false)
expect(actual).to be true/false #passes if actual == true/false
expect(actual).to be_nil #passes if actual is nil
expect(actual).to_not be_nil #passes if actual is not nil
Ranges
expect(1..10).to cover(3)
expect(actual).to be_between(min, max)
Expecting errors
expect { ... }.to raise_error expect { ... }.to raise_error(ErrorClass) expect { ... }.to raise_error("message") expect { ... }.to raise_error(ErrorClass, "message")
expect可以用于block也可以用于value expectations.
Expecting throws and Yielding没看懂⚠️
Compound Matcher Expressions
通过user,or可以创建混合匹配表达式 。
expect(stoplight.color).to eq("red").or eq("green").or eq("yellow")
expect(alphabet).to start_with("a").and end_with("z")
Composing Matchers
以下matchers接受matchers 作为参数。
- change().by(matcher) #改变sth等于by(匹配的值)
- change{}.from(mather).to(matcher) #改变sth,从matcher_val到mather_val
- include(matcher, matcher)
- include(:key => matcher, :other => mathcer)
‘change’ matcher:
- expect {do_sth}.to change(object, :attribute)
- expect {do_sth}.to change{object.attribute}
- 可以联合 from().to(); by(), by_at_least(), by_at_most()
Relish(n:great enjoyment; 水果蔬菜酱) 案例连接