我已經RSpec的控制器測試:Rspec的:測試控制器的所有動作
describe TestController do
it "test all actions" do
all_controller_actions.each do |a|
expect{get a}.to_not rais_error(SomeError)
end
end
end
如何實現all_controller_actions
方法?
我已經RSpec的控制器測試:Rspec的:測試控制器的所有動作
describe TestController do
it "test all actions" do
all_controller_actions.each do |a|
expect{get a}.to_not rais_error(SomeError)
end
end
end
如何實現all_controller_actions
方法?
雖然我寧願一個接一個地測試,但您的問題是可行的。
# Must state this variable to be excluded later because MyController has them.
a = ApplicationController.action_methods
m = MyController.action_methods
# Custom methods to exclude
e = %w{"create", "post}
@test_methods = m - a - e
describe TestController do
it "all GET actions got response" do
@test_methods.each do |t|
expect{get t}.to_not rais_error(SomeError)
end
end
end
更好的方法是爲控制器中的每個操作方法編寫不同的測試。
如果你看看on Rails的TestCase
類的文檔 - 這是從(甚至rspec的只是包裝這個類)創建控制器測試類,你會明白我的意思:
http://api.rubyonrails.org/classes/ActionController/TestCase.html
該文件說:
功能測試允許您測試每個測試方法單個控制器的動作。
的意圖是,控制器測試具有用於在控制器的每個動作的不同試驗方法。
我同意你的意見。但是這個代碼只是一個例子,如果你知道如何實現'all_controller_actions'方法 - 讓我知道。 – ole 2013-04-18 08:20:52
你的目標應該創建控制器的每個動作讓測試更具表現力和更容易理解不同的測試。每個動作主要位於自己的描述塊中,每個有意義的輸入都有自己的上下文塊。
有關示例:
describe "Users" do
describe "GET user#index" do
context "when the user is logged in" do
it "should render users#index"
end
context "when the user is logged out" do
it "should redirect to the login page"
end
end
end
的示例具有用於登錄和註銷的用戶,我們分離在它不同的上下文集團的describe "GET user#index"
塊下不同認證。你可以找到更詳細的解釋here。
動作,'POST','PUT','DELETE'中有多個'get'。 – 2013-04-18 02:37:46
同意@Kevin,不要試圖幹你的測試。否則,你將需要編寫測試測試:D – sameera207 2013-04-18 04:01:08
我沒有RESTful控制器與許多得到的行動,這個測試只是一個例子。 @Billy – ole 2013-04-18 08:09:32