首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Ruby on Rails 開發從頭來(二十三):功能測試慣用斷言與輔助方法完整參考

     編輯:Java 相關知識

HTTP 請求模擬方法

五大 HTTP 動詞對應方法,簽名一致:

get(action, parameters = nil, session = nil, flash = nil)
post(action, parameters = nil, session = nil, flash = nil)
put(action, parameters = nil, session = nil, flash = nil)
delete(action, parameters = nil, session = nil, flash = nil)
head(action, parameters = nil, session = nil, flash = nil)

參數說明

  • action:Symbol 或 String,控制器動作名稱
  • parameters:Hash,對應 params
  • session:Hash,預設 session 資料
  • flash:Hash,預設 flash 資料

範例

get :index
get :add_to_cart, :id => @product.id
post :save_order, :order => { :name => 'Fred', :email => 'fred@example.com' },
     :session => { :user_id => 1 }, :flash => { :notice => 'Welcome!' }

回應斷言

方法用途範例
assert_response(type, msg=nil)驗證 HTTP 狀態碼類別assert_response :success
assert_response 200
assert_response :redirect (300-399)
assert_redirected_to(options, msg=nil)驗證導向目標assert_redirected_to :action => 'index'
assert_redirected_to :controller => 'login', :action => 'login'
assert_redirected_to "https://example.com/page"
assert_template(expected, msg=nil)驗證渲染模板assert_template 'store/index'
assert_template 'layouts/application'

assert_response 符號對應:

  • :success → 200-299
  • :redirect → 300-399
  • :missing → 404
  • :error → 500-599

HTML 結構斷言

assert_tag(conditions)

conditions 為 Hash,支援鍵值:

鍵說明範例
:tag標籤名稱assert_tag :tag => 'html'
:content文字內容匹配assert_tag :content => "Welcome"
:attributes屬性 Hash 匹配assert_tag :tag => 'div', :attributes => { :class => 'error' }
:parent父節點條件assert_tag :tag => 'head', :parent => { :tag => 'html' }
:child第一個直屬子節點assert_tag :tag => 'html', :child => { :tag => 'head' }
:ancestor任一祖先節點assert_tag :tag => 'div', :ancestor => { :tag => 'form' }
:descendant任一子孫節點assert_tag :tag => 'form', :descendant => { :tag => 'input' }
:children子節點集合條件見下方

:children 進階選項

assert_tag :tag => 'ul',
           :children => { :count => 1..3,           # 子節點數量範圍
                          :less_than => 4,          # 少於 4 個
                          :greater_than => 0,       # 多於 0 個
                          :only => { :tag => 'li' } # 僅計算 li 標籤
                        }

測試上下文變數

請求執行後自動可用:

變數型別說明範例
assigns(key)Hash-like控制器實例變數assert_not_nil assigns(:products)
sessionHashSession 資料assert_equal 2, session[:cart].items.size
flashHashFlash 資料assert_equal "Login required", flash[:notice]
cookiesHashCookiesassert_equal "Fred", cookies[:name]
redirect_to_urlString完整導向 URLassert_equal "https://test.host/login", redirect_to_url

注意:assigns 鍵值需用 Symbol(:products),字串鍵("products")在某些版本不支援。

完整 API 參考

https://api.rubyonrails.com/classes/Test/Unit/Assertions.html

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved