2011-09-01 75 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