Active Model Lint 測試
在 TestCase 中包含 ActiveModel::Lint::Tests
,就能測試物件是否符合 Active Model API
。它會包含一些測試,這些測試會告訴你的物件是否完全相容,如果不是的話,則會告訴你未實作 API
哪些面向。
請注意,物件不一定非得實作所有 API 才能與 Action Pack 一起使用。此模組僅在您想要馬上使用所有功能時提供指導方針。
這些測試並不會嘗試判斷傳回值的語意正確性。例如,你可以實作 valid?
,讓它永遠都傳回 true
,而測試會通過。確認這些值的語意有意義,是你的責任。
預期你傳入的物件會對於 to_model
呼叫傳回相容的物件。to_model
傳回 self
是完全合理的。
- T
執行個體公用方法
test_errors_aref() 連結
如果物件的模型回應 errors
,且呼叫此方法的結果的 [](attribute)
傳回陣列,則通過測試,否則失敗。
errors[attribute]
用來擷取模型針對特定屬性的錯誤。如果存在錯誤,此方法應傳回一組字串,也就是針對涉案屬性的錯誤。如果使用在地化,這些字串應針對目前的語言環境進行在地化。如果沒有錯誤存在,此方法應傳回一個空的陣列。
test_model_naming() 連結
如果物件的模型可以對 model_name
回應(不論是作為執行個體方法,還是作為類別方法),且呼叫此方法傳回一個字串,以及一些方便使用的函式::human
、:singular
和 :plural
,則通過測試。
查看 ActiveModel::Naming
以取得更多資訊。
# File activemodel/lib/active_model/lint.rb, line 81 def test_model_naming assert_respond_to model.class, :model_name model_name = model.class.model_name assert_respond_to model_name, :to_str assert_respond_to model_name.human, :to_str assert_respond_to model_name.singular, :to_str assert_respond_to model_name.plural, :to_str assert_respond_to model, :model_name assert_equal model.model_name, model.class.model_name end
test_persisted?() 連結
如果物件的模型回應 persisted?
,且呼叫此方法傳回 true
或 false
,則通過測試,否則失敗。
計算物件的 URL 時,會使用 persisted?
。例如,如果物件未持久化,物件的表單將會導向建立動作。如果物件已持久化,物件的表單將會導向更新動作。
test_to_key() 連結
如果物件的模型回應 to_key
,且呼叫此方法傳回 nil
(表示物件尚未持久化),則通過測試,否則失敗。
to_key
傳回模型所有(主鍵)關鍵屬性的 Enumerable
,並用來為物件產生唯一的 DOM id。
來源:顯示 | 在 GitHub 上
# File activemodel/lib/active_model/lint.rb, line 31 def test_to_key assert_respond_to model, :to_key def model.persisted?() false end assert model.to_key.nil?, "to_key should return nil when `persisted?` returns false" end
test_to_param() 連結
如果物件的模型回應 to_param
,以及呼叫此方法時物件未持續時傳回 nil
,則通過。否則失敗。
to_param
用於表示網址中物件的鍵。實作方可以決定要引發例外或是在記錄使用複合主鍵時提供預設值。此行為在 lint 中沒有測試,因為強制實作方執行任何可能的實作策略是沒有意義的。
來源:顯示 | 在 GitHub 上
# File activemodel/lib/active_model/lint.rb, line 46 def test_to_param assert_respond_to model, :to_param def model.to_key() [1] end def model.persisted?() false end assert model.to_param.nil?, "to_param should return nil when `persisted?` returns false" end
test_to_partial_path() 連結
如果物件的模型回應 to_partial_path
,以及呼叫此方法時傳回字串,則通過。否則失敗。
to_partial_path
用於查詢部分。舉例而言,BlogPost 模型可能會傳回「blog_posts/blog_post」。
來源:顯示 | 在 GitHub 上
# File activemodel/lib/active_model/lint.rb, line 58 def test_to_partial_path assert_respond_to model, :to_partial_path assert_kind_of String, model.to_partial_path end