相等匹配器
Ruby 公开了几种不同的方法来处理相等性
a.equal?(b) # object identity - a and b refer to the same object
a.eql?(b) # object equivalence - a and b have the same value
a == b # object equivalence - a and b have the same value with type conversions
请注意,这些描述是指南,但没有被语言强制执行。任何对象都可以使用自己的语义实现这些方法中的任何一种。
rspec-expectations 附带与这些方法中的每一种一致的匹配器
expect(a).to equal(b) # passes if a.equal?(b)
expect(a).to eql(b) # passes if a.eql?(b)
expect(a).to be == b # passes if a == b
它还附带了两个更像 DSL 风格的匹配器
expect(a).to be(b) # passes if a.equal?(b)
expect(a).to eq(b) # passes if a == b
使用 eq (==) 比较
给定一个名为“compareusingeq.rb”的文件,其中包含
RSpec.describe "a string" do
it "is equal to another string of the same value" do
expect("this string").to eq("this string")
end
it "is not equal to another string of a different value" do
expect("this string").not_to eq("a different string")
end
end
RSpec.describe "an integer" do
it "is equal to a float of the same value" do
expect(5).to eq(5.0)
end
end
当我运行 rspec compare_using_eq.rb
那么输出应该包含“3 个示例,0 个失败”。
使用 == 比较
给定一个名为“compareusing==.rb”的文件,其中包含
RSpec.describe "a string" do
it "is equal to another string of the same value" do
expect("this string").to be == "this string"
end
it "is not equal to another string of a different value" do
expect("this string").not_to be == "a different string"
end
end
RSpec.describe "an integer" do
it "is equal to a float of the same value" do
expect(5).to be == 5.0
end
end
当我运行 rspec compare_using_==.rb
那么输出应该包含“3 个示例,0 个失败”。
使用 eql (eql?) 比较
给定一个名为“compareusingeql.rb”的文件,其中包含
RSpec.describe "an integer" do
it "is equal to another integer of the same value" do
expect(5).to eql(5)
end
it "is not equal to another integer of a different value" do
expect(5).not_to eql(6)
end
it "is not equal to a float of the same value" do
expect(5).not_to eql(5.0)
end
end
当我运行 rspec compare_using_eql.rb
那么输出应该包含“3 个示例,0 个失败”。
使用 equal (equal?) 比较
给定一个名为“compareusingequal.rb”的文件,其中包含
RSpec.describe "a string" do
it "is equal to itself" do
string = "this string"
expect(string).to equal(string)
end
it "is not equal to another string of the same value" do
expect("this string").not_to equal("this string")
end
it "is not equal to another string of a different value" do
expect("this string").not_to equal("a different string")
end
end
当我运行 rspec compare_using_equal.rb
那么输出应该包含“3 个示例,0 个失败”。
使用 be (equal?) 比较
给定一个名为“compareusingbe.rb”的文件,其中包含
RSpec.describe "a string" do
it "is equal to itself" do
string = "this string"
expect(string).to be(string)
end
it "is not equal to another string of the same value" do
expect("this string").not_to be("this string")
end
it "is not equal to another string of a different value" do
expect("this string").not_to be("a different string")
end
end
当我运行 rspec compare_using_be.rb
那么输出应该包含“3 个示例,0 个失败”。