代码之家  ›  专栏  ›  技术社区  ›  randombits

如何使这些RSpec测试在Rails中更加干燥

  •  2
  • randombits  · 技术社区  · 14 年前

      describe "authentication requests" do
        it "should return 401 for unauthenticated :show" do
          get :show
          ...
        end
    
        it "should return 401 for unauthenticated :create" do
          post :create
          ...
        end
      end
    

    有没有更好的方法来擦干这段代码,以便在一个测试中描述控制器中需要身份验证的任何操作?

    2 回复  |  直到 14 年前
        1
  •  8
  •   zetetic    14 年前

    如果需要跨控制器复制测试,可以使用rspec宏。创建 spec/macros/controller_macros.rb 用这样的方法:

    def should_return_401_for_unauthenticated(test_controller)
      describe test_controller, "authentication requests" do
        it "should return 401 for show" do
          get :show
          response.code.should == "401"
        end
        it "should return 401 for create" do
          post :create
          response.code.should == "401"
        end
      end
    end
    

    describe MyController do
        should_return_401_for_unauthenticated(self)
    end
    
        2
  •  1
  •   jenjenut233    14 年前

    describe "authentication requests" do
    
      limited_access = [:show, :create]
    
      limited_access.each do |action|
        it "should return 401 for unauthenticated :#{action}" do
          get action
          ## assert response 401
        end
      end
    
    end
    

    或者只做一次测试:

    describe "authentication requests" do
    
      limited_access = [:show, :create]
    
      it "should return 401 for unauthenticated #{limited_access.to_sentence}" do
        limited_access.each do |action|
          get action
          ## assert response 401
        end
      end
    
    end
    

    可以添加一个spec\u helper方法来为您抽象它。。。可能性是无穷的。