2010-09-23 38 views
2

我對我的一些控制器操作進行了一系列反覆測試,所有這些操作都需要身份驗證。其結果是,你最終看到很多類似的代碼如下:如何使這些RSpec測試在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 

有沒有更好的辦法了乾燥該代碼,以便在需要身份驗證可以在一個試驗中所描述的控制器的任何行動?

回答

8

如果需要跨控制器複製測試,可以使用rspec宏。在需要測試的每個控制器規格

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 
用的方法,像這樣創建 spec/macros/controller_macros.rb
0

我不是一個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_helper方法抽象爲你... 可能性是無止境。