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

Ruby on rails 如何使这些RSpec测试在Rails中更加干燥,ruby-on-rails,ruby,rspec,Ruby On Rails,Ruby,Rspec,我对一些控制器操作进行了一系列重复测试,所有这些都需要身份验证。因此,您最终会看到许多代码,如下所示: describe "authentication requests" do it "should return 401 for unauthenticated :show" do get :show ... end it "should return 401 for unauthenticated :create" do pos

我对一些控制器操作进行了一系列重复测试,所有这些都需要身份验证。因此,您最终会看到许多代码,如下所示:

  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

有没有更好的方法来干燥此代码,以便在一次测试中描述控制器中需要验证的任何操作?

我不是rspec用户,但您可以执行以下操作:

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助手方法来为您抽象它。。。可能性是无穷的。

如果需要跨控制器复制测试,可以使用rspec宏。使用如下方法创建
spec/macros/controller\u 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