2013-04-18 163 views
0

我已经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方法?

+0

动作,'POST','PUT','DELETE'中有多个'get'。 – 2013-04-18 02:37:46

+0

同意@Kevin,不要试图干你的测试。否则,你将需要编写测试测试:D – sameera207 2013-04-18 04:01:08

+0

我没有RESTful控制器与许多得到的行动,这个测试只是一个例子。 @Billy – ole 2013-04-18 08:09:32

回答

1

虽然我宁愿一个接一个地测试,但您的问题是可行的。

# 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 
2

更好的方法是为控制器中的每个操作方法编写不同的测试。

如果你看看on Rails的TestCase类的文档 - 这是从(甚至rspec的只是包装这个类)创建控制器测试类,你会明白我的意思:

http://api.rubyonrails.org/classes/ActionController/TestCase.html

该文件说:

功能测试允许您测试每个测试方法单个控制器的动作。

的意图是,控制器测试具有用于在控制器的每个动作的不同试验方法。

+0

我同意你的意见。但是这个代码只是一个例子,如果你知道如何实现'all_controller_actions'方法 - 让我知道。 – ole 2013-04-18 08:20:52

0

你的目标应该创建控制器的每个动作让测试更具表现力和更容易理解不同的测试。每个动作主要位于自己的描述块中,每个有意义的输入都有自己的上下文块。

有关示例:

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