使用 RSpec 比较值而不考虑地址
Compare values without regard to address using RSpec
使用RSpec,我想检查两个自定义对象的值是否相同。
假设我有一个 Person
class 具有 name
和 age
属性,并实例化两个对象。
person_1 = Person.new(name: 'Jack', age: 20)
person_2 = Person.new(name: 'Jack', age: 20)
要查看它们是否具有所有相同的属性,我不能使用 eq
匹配器,因为它们是两个不同的对象。
鉴于我没有使用 ActiveRecord,有没有一种方法可以不比较所有单独的属性?
应该对你有帮助:
https://github.com/TylerRick/active_record_ignored_attributes
a = Address.new(address: 'B St.')
b = Address.new(address: 'B St.')
a.same_as?(b) # => true
a = Address.new(address: 'B St.')
b = Address.new(address: 'Nowhere Road')
a.same_as?(b) # => false
我看到了两种主要的方法来做你想做的事。
您可以在 Person
class 上实施 a custom matcher or override the == method。第二个很好,因为你可以在其他地方使用相等性,甚至在测试之外。如果您要比较的内容非常具体(例如,您不关心特定测试中所有人的属性),则第一种方法很好。
使用RSpec,我想检查两个自定义对象的值是否相同。
假设我有一个 Person
class 具有 name
和 age
属性,并实例化两个对象。
person_1 = Person.new(name: 'Jack', age: 20)
person_2 = Person.new(name: 'Jack', age: 20)
要查看它们是否具有所有相同的属性,我不能使用 eq
匹配器,因为它们是两个不同的对象。
鉴于我没有使用 ActiveRecord,有没有一种方法可以不比较所有单独的属性?
应该对你有帮助:
https://github.com/TylerRick/active_record_ignored_attributes
a = Address.new(address: 'B St.')
b = Address.new(address: 'B St.')
a.same_as?(b) # => true
a = Address.new(address: 'B St.')
b = Address.new(address: 'Nowhere Road')
a.same_as?(b) # => false
我看到了两种主要的方法来做你想做的事。
您可以在 Person
class 上实施 a custom matcher or override the == method。第二个很好,因为你可以在其他地方使用相等性,甚至在测试之外。如果您要比较的内容非常具体(例如,您不关心特定测试中所有人的属性),则第一种方法很好。