Ruby on rails Rspec:所有控制器动作的测试

Ruby on rails Rspec:所有控制器动作的测试,ruby-on-rails,rspec,Ruby On Rails,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 如何实现所有\u控制器\u操作方法?更好的方法是为控制器中的每个操作方法编写不同的测试 如果您查看Rails上的文档TestCaseclass——创建

我有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

如何实现
所有\u控制器\u操作
方法?

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

如果您查看Rails上的文档
TestCase
class——创建控制器测试的类(即使rspec也只是包装了这个类),您将看到我的意思:

文件说:

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


其目的是控制器测试对控制器中的每个动作都有不同的测试方法。

虽然我更喜欢逐个测试,但您的问题是可行的

# 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

您应该针对控制器的每个动作创建不同的测试,以使测试更具表现力,更易于理解。每个动作大多位于自己的描述块中,每个有意义的输入都有自己的上下文块

例如:

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

该示例对登录用户和注销用户具有不同的身份验证,我们在
description“GET user#index”
块下的不同上下文块中对其进行了分隔。你可以找到更详细的解释。

在操作中有超过
get
POST
PUT
DELETE
。同意@Kevin的意见,不要尝试干燥你的测试。否则,您将需要为测试编写测试:DI没有包含许多get操作的RESTful控件,而此测试只是一个示例@我同意你的意见。但这段代码只是一个示例,如果您知道如何实现
所有控制器操作
方法,请告诉我。