執行 rake clone_structure_to_test 同步開發資料庫結構到測試庫。
定義 test/fixtures/products.yml:
version_control_book:
id: 1
title: Pragmatic Version Control
description: How to use version control
image_url: https://.../sk_svn_small.jpg
price: 29.95
date_available: 2005-01-26 00:00:00
automation_book:
id: 2
title: Pragmatic Project Automation
description: How to automate your project
image_url: https://.../sk_auto_small.jpg
price: 29.95
date_available: 2004-07-01 00:00:00
require File.dirname(__FILE__) + '/../test_helper'
class ProductTest < Test::Unit::TestCase
fixtures :products
def setup
@product = Product.find(1)
end
# ...
end
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 "https://.../sk_svn_small.jpg", @product.image_url
# 價欄位為 decimal,資料庫回傳 BigDecimal,測試用字串比對原始值
assert_equal "29.95", @product.price_before_type_cast
assert_equal "2005-01-26 00:00:00", @product.date_available_before_type_cast
end
def test_update
assert_equal "29.95", @product.price_before_type_cast
@product.price = 99.99
assert @product.save, @product.errors.full_messages.join("; ")
@product.reload
assert_equal "99.99", @product.price_before_type_cast
end
驗證存檔成功、重新載入後數值更新。
def test_destroy
@product.destroy
assert_raise(ActiveRecord::RecordNotFound) { Product.find(@product.id) }
end
刪除後查找應拋出 RecordNotFound 例外。
def test_validate
assert_equal "29.95", @product.price_before_type_cast
@product.price = 0.00
assert !@product.save
assert_equal 1, @product.errors.count
assert_equal "should be positive", @product.errors.on(:price)
end
模型定義 validates_numericality_of :price, :greater_than => 0,測試驗證邏輯生效。
depot> ruby test/unit/product_test.rb
Loaded suite test/unit/product_test
Started ...
Finished in 0.078 seconds.
3 tests, 10 assertions, 0 failures, 0 errors
所有 CRUD 與驗證測試通過。
price_before_type_cast 取得資料庫原始字串,避免 BigDecimal 比較問題reload 重新從資料庫載入,確認持久化成功assert_raise 區塊語法捕獲預期例外errors.on(:field) 取得特定欄位錯誤訊息