RSpec.configure和请求对象

Hec*_*tro 7 ruby rspec ruby-on-rails http ruby-on-rails-3.1

我有一个Rails 3.1应用程序,它是作为RESTful API构建的.该计划是基于通过Authorization HTTP标头在每个请求上传递的API密钥来处理身份验证.为了在RSpec中测试它,我想request.env["HTTP_AUTHORIZATION"]config.before块中设置属性:

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

不幸的是,这会引发异常,因为块request中不存在该对象config.before.

是否有另一种方法来设置此标头,将其包含在before每个控制器测试文件的块中?

iaf*_*nov 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
Run Code Online (Sandbox Code Playgroud)