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

來源:互聯網
上載者:User

上次測試Modeul的問題還沒有解決,但是下面的還要繼續,這次來測試Controller。

1.在test\functional目錄下,rails已經為我們的controller產生了對應的測試檔案,要注意application_controller不會產生測試檔案。我們以控制登入的LoginController為例,開啟login_controller_test.rb,內容如下:

require File.dirname(__FILE__) + '/../test_helper'require 'login_controller'  # Re-raise errors caught by the controller.class LoginController; def rescue_action(e) raise e end; end  class LoginControllerTest < Test::Unit::TestCasedef setup@controller = LoginController.new@request  = ActionController::TestRequest.new@response  = ActionController::TestResponse.newend# Replace this with your real tests.def test_truthassert trueendend

我們看到,在setup方法裡,定義了三個對象@controller和@request和@response,這樣,我們就可以在不接入webserver或network的情況下進行測試了。

2.我們來把其中的test_truth方法替換成下面的代碼:

def test_indexget :indexassert_response :successend

其中,get方法類比發出一個web請求,請求的action是index,並且捕捉響應(response),然後由assert_response斷言來判斷響應是否成功。

現在運行測試:depot>ruby test/functional/login_controller_test.rb

會看到測試失敗了,命令列的輸出:

Expected response to be a <:success>, but was <302>1 tests, 1 assertions, 1 failures, 0 errors

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.