上篇隨筆簡單瞭解了rails的測試和測試用資料的使用,這次來看看怎樣對一個model進行添刪查改的測試。
1.還是使用上次寫的products_test.rb,修改test_turth方法的名字為test_create,並且使其內容為:
def test_create assert_kind_of Product, @product assert_equal 1, @product.id assert_equal "Pragmatic Version Control", @product.title assert_equal "How to use version control", @product.description assert_equal "http://.../sk_svn_small.jpg", @product.image_url assert_equal 29.95,@product.price assert_equal "2005-01-26 00:00:00", @product.date_available_before_type_cast end
然後運行測試命令:depot>ruby test/unit/product_test.rb,螢幕上會顯示資訊:
Loaded suite test/unit/product_testStartedFFinished in 0.109 seconds.1) Failure:test_create(ProductTest) [test/unit/product_test.rb:16]:<29> expected but was<#<BigDecimal:4aad7b0,'0.2995E2',8(8)>>.1 tests, 6 assertions, 1 failures, 0 errors
我們看到,是assert_equal 29.95,@product.price宣告失敗了。根據《Agile Web Development with Rails》裡的內容,這句斷言應該是正常通過的。但是不知道是不是版本或環境的問題,我自己寫的時候總是不行。為了能夠使斷言通過,我們修改一下,把
assert_equal 29.95,@product.price
改為:assert_equal "29.95",@product.price_before_type_cast
我們看到了,product對象的每個屬性都有對應的_before_type_cast版本,其內容是一個字串。
現在再次運行測試命令,得到的結果如下:
Loaded suite test/unit/product_testStarted.Finished in 0.078 seconds.
1 tests, 7 assertions, 0 failures, 0 errors
從上面的測試中看到,我們在setup方法中,從資料庫中尋找了id為1的記錄,然後在test_create方法中對其的屬性逐個判斷測試。