天天看點

[AWDwR4] Iteration E 中遇到的問題彙總

Q1. teration E1中,p142頁 執行rake test:units 後出錯:

1) Failure:
test_product_price_must_be_positive(ProductTest) [/home/csd/railsProjects/depot/test/unit/product_test.rb:36]:
Failed assertion, no message given.      

看代碼好像沒什麼錯誤的地方,hailong提醒我可以用 rails console --sandbox 指令, 使用 --sandbox 參數時, 對資料庫的所有修改都會在退出console時復原。我按照測試用例中的資料new了一個 Product p,然後檢視p的valid屬性,果然為false,再去檢視 p.errors資訊,發現是我照着書上的代碼寫例子時,嫌 title字段太長了,随手輸的title太短了導緻的。在rails console中輸入的指令如下:

1.9.3p194 :001 > p = Product.new(:title => "Awd sds",
1.9.3p194 :002 >     :description => "yyy",
1.9.3p194 :003 >     :image_url => "fred.jpg",
1.9.3p194 :004 >     :price => 1 )
1.9.3p194 :005 > p.valid?
 Product Exists (0.2ms)  SELECT 1 AS one FROM "products" WHERE "products"."title" = 'Awd sds' LIMIT 1
 => false
1.9.3p194 :006 > p.errors
 => #<ActiveModel::Errors:0x0000000326ecf8 @base=#<Product id: nil, title: "Awd sds", description: "yyy", image_url: "fred.jpg", price: #<BigDecimal:3371808,'0.1E1',9(36)>, created_at: nil, updated_at: nil>, @messages={:title=>["It's too short"]}>      

PS:

  跑測試時,如果想在測試過程中列印一些資訊,可以使用 puts 來輸出資訊,rails 3 中,使用 rake 時加上 --trace 參數或者使用

ruby -Itest test/unit/product_test.rb 也可以,參考連結

回到本系列的目錄