2011-09-01 70 views
7

我有一個Rails 3.1應用程序被構建爲一個RESTful API。該計劃是基於通過授權HTTP頭在每個請求上傳遞的API密鑰來處理認證。爲了在RSpec中測試這一點,我想設置在config.beforerequest.env["HTTP_AUTHORIZATION"]屬性:RSpec.configure和請求對象

RSpec.configure do |config| 
    config.mock_with :rspec 
    config.use_transactional_fixtures = true 
    config.before(:each) do 
    # Set API key in Authorization header 
    request.env["HTTP_AUTHORIZATION"] = "6db13cc8-815f-42ce-aa9e-446556fe3d72" 
    end 
end 

不幸的是,這是因爲request對象不在config.before塊內拋出異常。

是否有另一種方法來將此標題設置在每個控制器測試文件的before塊中,包括 ?

回答

2

我還沒有嘗試過自己,但也許創建共享實例組可以幫助你理清你的問題:

shared_examples_for "All API Controllers" do 
    before(:each) do 
    request.env["HTTP_AUTHORIZATION"] = "blah" 
    end 

    # ... also here you can test common functionality of all your api controllers 
    # like reaction on invalid authorization header or absence of header 
end 

describe OneOfAPIControllers do 
    it_should_behave_like "All API Controllers" 

    it "should do stuff" do 
    ... 
    end 
end