在Rails 4控制器中使用時處理關注點測試的最佳方式是什麼?說我有一個微不足道的關注Citations
。如何在Rails 4中測試Controller關注點
module Citations
extend ActiveSupport::Concern
def citations ; end
end
被測預期的行爲是任何控制器,其中包括這個問題會得到這個citations
端點。
class ConversationController < ActionController::Base
include Citations
end
簡單。
ConversationController.new.respond_to? :yelling #=> true
但是,單獨測試這種擔憂的正確方法是什麼?
class CitationConcernController < ActionController::Base
include Citations
end
describe CitationConcernController, type: :controller do
it 'should add the citations endpoint' do
get :citations
expect(response).to be_successful
end
end
不幸的是,這將失敗。
CitationConcernController
should add the citations endpoint (FAILED - 1)
Failures:
1) CitationConcernController should add the citations endpoint
Failure/Error: get :citations
ActionController::UrlGenerationError:
No route matches {:controller=>"citation_concern", :action=>"citations"}
# ./controller_concern_spec.rb:14:in `block (2 levels) in <top (required)>'
這是一個人爲的例子。在我的應用程序中,我收到了另一個錯誤。
RuntimeError:
@routes is nil: make sure you set it in your test's setup method.
這個測試可以絕對重要!因爲它會孤立地測試問題,但是如果您在3個控制器之間共享這些問題並且您沒有共享示例。如果有人從某個控制器中接受了包含MyControllerConcern的測試,測試不會失敗,並且錯誤會通過不明顯的...所以即使您進行了隔離測試,您仍然需要共享示例來確保您的控制器執行他們應該做的做。在這種情況下,進行此測試是一種矯枉過正的行爲,因爲您應該已經有了共享示例...... –
這就是爲什麼您要使用集成。這裏的主題是單元測試。你是對的:單元測試包括關注模塊是一個好主意:只需對祖先進行測試就足夠了。 – Benj
僅供參考:'Object#remove_const'是私有的,這就是爲什麼我們必須使用'send' – Dorian