首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Ruby on Rails 開發從頭來(二十):模型 CRUD 測試實作

     編輯:Java 相關知識

測試環境準備

執行 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) 取得特定欄位錯誤訊息
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved