简体   繁体   English

Rspec:测试所有控制器动作

[英]Rspec: test for all controller actions

I have rspec controller test:我有 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

How to implement all_controller_actions method?如何实现all_controller_actions方法?

A better way is to write a different test for each action method in the controller.更好的方法是为控制器中的每个操作方法编写不同的测试。

If you look at the docs on Rails TestCase class -- the class that controller tests are created from (even rspec just wraps this class), you'll see what I mean:如果你查看 Rails TestCase类的文档——控制器测试是从这个类创建的(甚至 rspec 只是包装了这个类),你就会明白我的意思:

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

The docs say:文档说:

Functional tests allow you to test a single controller action per test method.功能测试允许您测试每个测试方法的单个控制器操作。

The intention is that controller tests have a different test method for each action in the controller.目的是控制器测试对控制器中的每个动作都有不同的测试方法。

While I prefer to test one by one, your question is doable.虽然我更喜欢一一测试,但您的问题是可行的。

# 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

You should aim to create a different test for each action of the controller to make tests more expressive and easier to understand.您应该致力于为控制器的每个操作创建不同的测试,以使测试更具表现力且更易于理解。 Each action would mostly be located in its own describe blocks, with each meaningful input having its own context block.每个动作大多位于其自己的描述块中,每个有意义的输入都有自己的上下文块。

For an example:例如:

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

The example has different authentications for logged in and logged out users, we separated it in different context blocs under the describe "GET user#index" block.该示例对登录和注销的用户具有不同的身份验证,我们将其分隔在describe "GET user#index"块下的不同上下文块中。 You can find a more detailed explanation here .您可以在此处找到更详细的说明。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM