Ruby on rails開發從頭來(windows)(二十)-測試model(CRUD)

來源:互聯網
上載者:User

上篇隨筆簡單瞭解了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方法中對其的屬性逐個判斷測試。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.