2013-03-15 22 views
3

我無法理解正在閱讀的書上的一段代碼。assert_equal語法

下面的代碼:

test "product price must be positive" do 
    product = Product.new(:title => "My Book Title", :description => "yyy", :image_url => "zzz.jpg") 
    product.price = -1 

    assert product.invalid? 
    assert_equal "must be greater than or equal to 0.01", product.errors[:price].join('; ') 

    product.price = 0 
    assert product.invalid? 

    assert_equal "must be greater than or equal to 0.01", product.errors[:price].join('; ') 
    product.price = 1 
    assert product.valid? 
end 

形式Ruby文檔我:

assert_equal(EXP,行爲,味精=無)

失敗,除非EXP ==行爲打印如果可能,兩者之間的區別。

是嗎假設行:

assert_equal 「必須大於或等於0.01」,

指:

assert_equal(「必須是大於或等於0.01「,)#沒有行爲或味精。

另外,有人可以解釋什麼陣列是下面的線使用和爲什麼?

product.errors [:價格]。加入( ';')

我不能把握哪來的陣列,什麼是筆者通過連接實現。

在此先感謝您的任何信息。

這本書是:使用Rails第四版敏捷Web開發

回答

2

完整的說法是在一個行,如下所示:

assert_equal "must be greater than or equal to 0.01" , product.errors[:price].join('; ') 

這裏,exp = "must be greater than or equal to 0.01"act = product.errors[:price].join('; ')

product.errors[:price]是一個數組,接收多個錯誤消息。

鏈接.join(';')它使所有的錯誤消息連接在一起';'作爲分隔符。

在這種情況下,只有一個錯誤("must be greater than or equal to 0.01"),因此join method只是在不添加分隔符的情況下返回相同的值。因此,斷言應該通過。

實施例來說明的join(';')行爲在這種情況下:

> ['a', 'b'].join(';') 
=> "a;b" 

> ['a'].join(';') 
=> "a" 
+2

的錯誤是一個陣列型的對象,所以一個'join'需要將它們呈現爲一個字符串。 – tadman 2013-03-15 18:46:56

+0

非常感謝您的回答,我拒絕繼續閱讀這本書,因爲我無法理解這段代碼。 – 2013-03-15 19:39:42

+0

從書中學習的過程中令人敬佩的精神! – 2013-03-16 04:10:20