Ruby on rails開發從頭來(windows)(二十四)-測試Controller

來源:互聯網
上載者:User

上篇隨筆裡介紹了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中尋找問題。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.