Ruby on rails開發從頭來(windows)(十九)-測試開始

前面我們已經完成了一個簡單的購物車,從這篇開始我們看看在rails中怎樣進行測試。

 

在我們創建購物車程序的時候在我們的depot目錄下,就已經有一個test目錄了,這就是爲我們進行測試準備的。到目前爲止,我們看到裏面的fixtrues和functional,unit目錄中已經有對controller和model對應的測試文件。

我們首先測試一下products這個model。代碼test\unit目錄下的product_test.rb文件,修改其內容爲:

require File.dirname(__FILE__) + '/../test_helper'

 

class ProductTest < Test::Unit::TestCase

  fixtures :products

  def setup

    @product = Product.find(1)

  end

 

  # Replace this with your real tests.

  def test_truth

    assert true

  end

end

然後在命令行裏運行測試命令: \rails_apps\depot>ruby test/unit/product_test.rb,將會看到下面的輸出:

Loaded suite test/unit/product_test

Started

E

Finished in 0.312 seconds.

 

1) Error:

test_truth(ProductTest):

ActiveRecord::StatementInvalid: Mysql::Error: Table 'depot_test.products' doesn't exist: DELETE FROM products

………

1 tests, 0 assertions, 0 failures, 1 errors

從上面的信息可以看到,是在depot_test數據庫中沒有products這個表。這是因爲,我們在創建一個rails項目的時候,對應的在mysql中創建了三個庫:development,test,production,我們之前編寫代碼使用的都是development庫,現在進行測試,rails使用的是test庫。我們現在要作的就是在test庫裏創建products表,你可以使用sql語句來進行表創建的工作,但是rails給我們提供了更方便的辦法,在命令行裏使用rake命令:

depot>rake clone_structure_to_test

這樣就會development庫的結構克隆到test庫,完成後會看到在test庫裏已經有我們用到的四個表了。

 

完成後我們要給products造一些測試數據。我們打開fixtures目錄下的products.yml文件,修改裏面的內容:

# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html

version_control_book:

  id:             1

  title:          Pragmatic Version Control

  description:    How to use version control

  image_url:      http://.../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:      http://.../sk_auto_small.jpg

  price:          29.95

  date_available: 2004-07-01 00:00:00

在rails裏,一個fixture就代表了一個model的初始的內容,這裏,我們包含了兩個fixture:version_control_book和automation_book。每個fixture的內容都由列名和對應的內容組成,並且由冒號和空格隔開(Tab是不行的)如果在運行測試的時候提示:

Fixture::FormatError: a YAML error occurred parsing………

那麼肯定是yml文件的格式問題。

 

定義好了fixture,怎樣使用它呢?回頭看看上面的products_test.rb文件,裏面有一句:fixtures :products,作爲約定,products_test將從products.yml里加載fixture。下面我們再次運行測試命令:

depot>ruby test/unit/product_test.rb

這次正確執行了,屏幕上會顯示信息:

 Loaded suite test/unit/product_test

Started

.

Finished in 0.063 seconds.

 

1 tests, 1 assertions, 0 failures, 0 errors

再回頭看數據庫裏,products表中新插入了兩條記錄,和我們在products.yml文件中作配置的一樣。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章