上篇隨筆裡介紹了rails在功能測試方面的一些約定。這次我們繼續會到Controller的測試。
之前我們測試的是login,可以相見,使用者在login以後就要開始進行購物的動作了,所以我們現在就來測試store_controller,我們先來測試index方法。
1.在index裡,我們列出了所有的可以銷售的書籍的列表,所以,這裡我們要讓store_controller來使用product.yml和orders.yml裡的資料。現在來看看store_controller_test.rb檔案,完整內容如下:
require File.dirname(__FILE__) + '/../test_helper'require 'store_controller'# Re-raise errors caught by the controller.class StoreController; def rescue_action(e) raise e end; endclass StoreControllerTest < Test::Unit::TestCasefixtures :products, :ordersdef setup@controller = StoreController.new@request = ActionController::TestRequest.new@response = ActionController::TestResponse.newend# Replace this with your real tests.def teardown LineItem.delete_allendend
要注意到我們這裡的teardown方法,添加這個方法是因為我們將要寫的一些測試會間接的將一些LineItem存入資料庫中。在所有的測試方法後面定義這個teardown方法,可以很方便的在測試執行後刪除測試資料,這樣就不會影響到其他的測試。在調用了LineItem.delete_all之後,line_item表中所有的資料都會被刪除。通常情況下,我們不需要這樣作,因為fixture會替我們清除資料,但是這裡,我們沒有使用line_item的fixture,所以我們要自己來作這件事情。
2.接下來我們添加一個test_index方法:
def test_index get :index assert_response :success assert_equal 2, assigns(:products).size assert_template "store/index" end
因為我們在前面的Model的測試裡已經測試了Products的CRUD,所以這裡,我們測試index的Action,並且看看Products的個數,是不是使用了指定的View來描畫(render)頁面。
我們在Controller中使用了Model,如果Controller的測試失敗了,而Model的測試通過了,那麼一般就要在Controller中尋找問題,如果Controller和Model的測試都失敗了,那麼我們最好在Model中尋找問題。