exist
匹配器
exist
匹配器用于指定某些东西存在(如 #exist?
或 #exists?
所示)
expect(obj).to exist # passes if obj.exist? or obj.exists?
基本用法
给定一个名为“existmatcherspec.rb”的文件,内容如下:
class Planet
attr_reader :name
def initialize(name)
@name = name
end
def inspect
"<Planet: #{name}>"
end
def exist? # also works with exists?
%w[Mercury Venus Earth Mars Jupiter Saturn Uranus Neptune].include?(name)
end
end
RSpec.describe "Earth" do
let(:earth) { Planet.new("Earth") }
specify { expect(earth).to exist }
specify { expect(earth).not_to exist } # deliberate failure
end
RSpec.describe "Tatooine" do
let(:tatooine) { Planet.new("Tatooine") }
specify { expect(tatooine).to exist } # deliberate failure
specify { expect(tatooine).not_to exist }
end
当我运行 rspec exist_matcher_spec.rb
那么输出应该包含以下所有内容
4 个示例,2 个失败 |
预期 |
预期 |