2013-06-03 68 views
-2

我不確定如何通過以下測試用例。我用源聯合(|)和內部list.include(源)我如何覆蓋與無字段紅寶石平等?

class Source 
    # mongoid object code... 
    def hash 
    url.hash 
    end 

    def ==(other) 
    eql?(other) 
    end 

    def eql?(other_source) 
    url = self.url and other_source and url == other_source.url 
    end 
end 

測試用例:

ext1 = Source.new 
    ext2 = Source.new(url: "test") 

    (ext2.== ext1).should    == false # false 
    (ext1.== ext2).should    == false # is returning nil instead of false 

我想有最後的情況下返回false,而不是零,但我不知道?如何發生這種事情?

回答

1

這種情況的常見模式是「雙砰」的表達:

!!(url = self.url && other_source && url == other_source.url) 

這將任何值強制到truefalse

(另外,the Ruby style guide建議代替andor使用&&||

1

當我運行你的代碼,然後點擊行

ext2 = Source.new(url: "test") 

我得到ArgumentError: wrong number of arguments(1 for 0),所以我不知道如果這可以工作,但也許你的意思是

def eql?(other_source) 
    url == self.url and other_source and url == other_source.url 
    end 
0

我不確定你是否一定要粘貼一些代碼,但我認爲你的意思是這樣的:

class Source 
    attr_reader :url 

    def initialize(params = {}) 
    @url = params[:url] 
    end 

    def hash 
    @url.hash 
    end 

    def ==(other) 
    eql?(other) 
    end 

    def eql?(other_source) 
    other_source && @url == other_source.url 
    end 
end 

這同時固定幾個人解決您的問題:

  1. 你需要一個實例變量命名爲url和一個getter它。
  2. 您需要一個initialize方法。

eql?然後只需要確保other_sourcenil和比較url S:

ext2.== ext1 # => false 
ext1.== ext2 # => false 
1

爲什麼url變量呢?

# if they need to be the same class to be equal 
def eql(other_source) 
    Source === other_source && other_source.url == self.url 
end 

# OR, if it just matters that it responds to url 
def eql(other_source) 
    other_source.respond_to?(:url) && other_source.url == self.url 
end 

注意,只爲other_source的感實性測試並不能阻止一個異常,如果它truthy,仍然沒有一個url屬性,因此,如果你說你目前的解決方案將引發異常,例如ext1 == true

這是不用提,在你的榜樣,ext1絕不可能eql什麼,因爲你正在測試的第一件事情是self.url存在。這是你想要的嗎?如果這是標準,是否至少有兩個沒有url的來源被認爲是相等的?