2012-11-04 18 views
0

用於在使用Rails書敏捷Web開發括號:爲什麼,他們是教學中如何寫測試單元的情況下在此assert_equal聲明

test "product price must be positive" do 
    product = Product.new(title: "By 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] 
end 

關於assert_equal聲明,爲什麼周圍的需要括號「必須大於...「字符串。我假設變量類型在這裏發揮作用,但需要澄清一些原因。

謝謝。

回答

1

model.errors[:field]總是返回一個字符串數組,即使只有一個錯誤。

如果聲明是在沒有[]的情況下完成的,它總會是錯誤的,因爲它會將字符串與數組進行比較。

assert_equal "must be greater than or equal to 0.01", ["must be greater than or equal to 0.01"]  
=> false 

assert_equal ["must be greater than or equal to 0.01"], ["must be greater than or equal to 0.01"] 
=> true 
+0

啊哈!因此,如果該字段有多個錯誤,assert_equal是否嘗試與其他返回的錯誤找到匹配項,還是隻嘗試匹配第一個錯誤? – uberdanzik

+0

如果該字段有多個錯誤,斷言將失敗。數組中的所有內容/元素必須相同。 – pjumble

+0

因此,聽起來好像有一種更好的方法可以做到這一點,以後我會在書中學習。感謝您幫助我瞭解類型問題! – uberdanzik

相關問題