复合期望
可以使用 and
或 or
组合匹配器来创建复合期望。
使用 and
链式期望
给定一个名为“compoundandmatcher_spec.rb”的文件,其中包含
RSpec.describe "A compound `and` matcher" do
let(:string) { "foo bar bazz" }
it "passes when both are true" do
expect(string).to start_with("foo").and end_with("bazz")
end
it "passes when using boolean AND `&` alias" do
expect(string).to start_with("foo") & end_with("bazz")
end
it "fails when the first matcher fails" do
expect(string).to start_with("bar").and end_with("bazz")
end
it "fails when the second matcher fails" do
expect(string).to start_with("foo").and end_with("bar")
end
end
当我运行 rspec compound_and_matcher_spec.rb
时
则输出应包含“4 个示例,2 个失败”。
使用 or
链式期望
给定一个名为“stoplight_spec.rb”的文件,其中包含
class StopLight
def color
%w[ green yellow red ].shuffle.first
end
end
RSpec.describe StopLight, "#color" do
let(:light) { StopLight.new }
it "is green, yellow or red" do
expect(light.color).to eq("green").or eq("yellow").or eq("red")
end
it "passes when using boolean OR `|` alias" do
expect(light.color).to eq("green") | eq("yellow") | eq("red")
end
end
当我运行 rspec stoplight_spec.rb
时
则该示例应通过。