我在ruby中创建了两个具有完全相同属性和值的不同对象。
我现在要比较两个对象的内容是否相同,但以下比较:
actual.should == expected
actual.should eq(expected)
actual.should (be expected)
失败了:
Diff:
@@ -1,4 +1,4 @@
-#<Station:0x2807628
+#<Station:0x2807610
在rspec / ruby中有没有办法轻松实现这个目标?
干杯!!
答案 0 :(得分:11)
执行此操作的惯用方法是覆盖#==
运算符:
class Station
def ==(o)
primary_key == o.primary_key
end
def hash
primary_key.hash
end
end
执行此操作时,通常也要覆盖#hash
方法。覆盖#eql?
或#equal?
编辑:您在此特定情况下可以执行的另一项操作是custom RSpec matcher。
答案 1 :(得分:2)
使用have_attributes匹配器指定对象的属性与预期属性匹配:
Person = Struct.new(:name, :age)
person = Person.new("Jim", 32)
expect(person).to have_attributes(:name => "Jim", :age => 32)
expect(person).to have_attributes(:name => a_string_starting_with("J"), :age => (a_value > 30) )
答案 2 :(得分:1)
有点晚了,但你可以序列化它,例如:
require 'json'
expect(actual.to_json).to eq(expected.to_json) #new rspec syntax
actual.to_json.should eq(expected.to_json) #old rspec syntax
答案 3 :(得分:0)
也许您应该考虑在对象上重载相等的运算符。
答案 4 :(得分:-1)
它对我有用!我遇到了同样的问题
code39