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

ran*_*its 2 ruby rspec ruby-on-rails

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

  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
Run Code Online (Sandbox Code Playgroud)

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

zet*_*tic 8

如果需要跨控制器复制测试,可以使用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
Run Code Online (Sandbox Code Playgroud)

然后在每个需要测试的控制器规范中:

describe MyController do
    should_return_401_for_unauthenticated(self)
end
Run Code Online (Sandbox Code Playgroud)