之前我們測試的是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; end
class StoreControllerTest < Test::Unit::TestCase
fixtures :products, :orders
def setup
@controller = StoreController.new
@request = ActionController::TestRequest.new
@response = ActionController::TestResponse.new
end
# Replace this with your real tests.
def teardown
LineItem.delete_all
end
end
要注意到我們這裏的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中查找問題。
3. 測試add_to_cart方法:
在測試類裏添加方法:
def test_add_to_cart
get :add_to_cart, :id => @version_control_book.id
cart = session[:cart]
assert_equal @version_control_book.price, cart.total_price
assert_redirected_to :action => 'display_cart'
follow_redirect
assert_equal 1, assigns(:items).size
assert_template "store/display_cart"
end
然後運行測試,如果你和我一樣不幸的話,會提示@version_control_book對象爲nil,這個問題是以前在測試Product的Model時遺留的問題,爲了不影響學習的大計,這個地方我們給改改,好讓這個系列能繼續:
def test_add_to_cart
@product = Product.find(1)
get :add_to_cart, :id => @product.id
cart = session[:cart]
assert_equal @product.price, cart.total_price
assert_redirected_to :action => 'display_cart'
follow_redirect
assert_equal 1, assigns(:items).size
assert_template "store/display_cart"
end
標示爲藍色的代碼是我們修改的地方,再次運行測試看看:
Finished in 0.156 seconds.
2 tests, 7 assertions, 0 failures, 0 errors
嗯,測試全部通過。
在這裏要注意在頁面的重定向的斷言後,調用了follow_redirect,這是模擬瀏覽器重定向到一個新的頁面。這樣做是讓assign是可變的,並且,assert_template斷言使用display_cart Action的結果,而不是之前的add_to_cart的結果,這樣,display_cart的Action會描畫display_cart.html視圖。
4. 下面我們繼續測試用戶向購物車中添加一個不存在的product的情況,因爲用戶可能直接在瀏覽器地址欄中輸入地址,導致一個不存在的product的id,添加test_add_to_cart_invalid_product方法:
def test_add_to_cart_invalid_product
get :add_to_cart, :id => '-1'
assert_redirected_to :action => 'index'
assert_equal "Invalid product", flash[:notice]
end
運行測試,成功了。
好了,這次就到這裏。