2012-12-16 39 views
8

我使用完全相同的屬性和值在ruby中創建了2個不同的對象。Ruby/Rspec:可以比較兩個對象的內容嗎?

我現在想比較這兩個對象的內容是相同的,但以下比較:

actual.should == expected 
actual.should eq(expected) 
actual.should (be expected) 

失敗:

Diff: 
    @@ -1,4 +1,4 @@ 
    -#<Station:0x2807628 
    +#<Station:0x2807610 

是否有rspec的/紅寶石任何方式輕鬆實現這一目標?

乾杯!

回答

0

也許你應該考慮在對象上重載相等的運算符。

9

一種慣用的方法,這樣做是爲了覆蓋#==操作:

class Station 
    def ==(o) 
    primary_key == o.primary_key 
    end 

    def hash 
    primary_key.hash 
    end 
end 

當你這樣做,你一般要重寫#hash方法爲好。覆蓋#eql?#equal?的情況較少見。

編輯:你可以在這種特殊情況下,不涉及覆蓋#==做的另一件事,就是讓一個custom RSpec matcher

+0

嗨埃裏克,謝謝你的答案,試圖理解這種方法。爲什麼我們需要重寫'#hash'以及何時會被調用? 我們應該如何實現這種比較,例如'station_one。==(station_two)''? – mickael

+0

@mickael:沒問題。您需要重寫'#hash',以便在您將其用作Hash對象中的鍵時,該對象的行爲繼續有意義。您只需在'it'塊或類似內容中執行'obj1.should == obj2',就可以在'Rspec'中使用重寫的'#=='運算符。 –

2

有點晚了,但你可以把它序列化,每例如:

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 
0

使用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)) 

Relishapp RSpec Docs