国产一区二区精品久久_蜜桃狠狠狠狠狠狠狠狠狠_午夜视频精品_激情都市一区二区

當前位置:首頁 > 網站舊欄目 > 學習園地 > 設計軟件教程 > 每天一劑Rails良藥之Testing Across Multiple Controllers

每天一劑Rails良藥之Testing Across Multiple Controllers
2010-01-14 07:09:34  作者:  來源:
Rails測試分三種:
1,關注于一個單獨的Model的單元測試Unit test
2,關注于一個單獨的Controller和它使用的models之間的交互的功能測試Functional test
3,關注story級的多個controllers的多個actions之間的交互的集成測試Integration test
今天我們就來看看跨越多個controllers的集成測試
IntegrationTesting/test/integration/stories_test.rb
Java代碼 復制代碼
  1. require "#{File.dirname(__FILE__)}/../test_helper"  
  2.   
  3. class StoriesTest < ActionController::IntegrationTest   
  4.   fixtures :accounts, :ledgers, :registers, :people   
  5.   
  6.   def test_signup_new_person   
  7.     go_to_login   
  8.     go_to_signup   
  9.     signup :name => "Bob",   
  10.            :user_name => "bob",   
  11.            :password => "secret"  
  12.   end   
  13.   
  14.   private  
  15.   def go_to_login   
  16.     get "/login"  
  17.     assert_response :success   
  18.     assert_template "login/index"  
  19.   end   
  20.   
  21.   def go_to_signup   
  22.     get "/signup"  
  23.     assert_response :success   
  24.     assert_template "signup/index"  
  25.   end   
  26.   
  27.   def signup(options)   
  28.     post "/signup", options   
  29.     assert_response :redirect   
  30.     follow_redirect!   
  31.     assert_response :success   
  32.     assert_template "ledger/index"  
  33.   end   
  34. end  

其中我們將一些通用的流程做成helper方法,如go_to_login,go_to_signup,signup
我們甚至可以將登錄認證等通用流程做成一個helper方法并放在我們自己的DSL模塊里:
Java代碼 復制代碼
  1. require "#{File.dirname(__FILE__)}/../test_helper"  
  2.   
  3. class StoriesTest < ActionController::IntegrationTest   
  4.   fixtures :accounts, :ledgers, :registers, :people   
  5.   
  6.   def test_multiple_users   
  7.     jim = new_session_as(:jim)   
  8.     bob = new_session_as(:bob)   
  9.     stacey = new_session_as(:stacey)   
  10.   
  11.     jim.selects_ledger(:jims)   
  12.     jim.adds_account(:name => "checking:)   
  13.     bob.goes_to_preferences   
  14.     stacey.cancels_account   
  15.   end   
  16.   
  17.   private  
  18.   
  19.   module MyTestingDSL   
  20.     attr_reader :person   
  21.   
  22.     def logs_in_as(person)   
  23.       @person = people(person)   
  24.       post authenticate_url, :user_name => @person.user_name, :password => @person.password   
  25.       is_redirected_to "ledger/list"  
  26.     end   
  27.   
  28.     def goes_to_preferences   
  29.       # ...   
  30.     end   
  31.   
  32.     def cancels_account   
  33.       # ...   
  34.     end   
  35.   
  36.     def new_session_as(person)   
  37.       new_session do |sess|   
  38.         sess.goes_to_login   
  39.         sess.logs_in_as(person)   
  40.         yield sess if block_given?   
  41.       end   
  42.     end   
  43. end  

我們會發現集成測試比單獨Controller的功能測試慢許多,因為集成測試涉及的東西太多

安徽新華電腦學校專業職業規劃師為你提供更多幫助【在線咨詢