RSpec.configure和请求对象

时间:2011-09-01 22:37:55

标签: ruby-on-rails ruby http rspec 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

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

是否有另一种方法可以将此标题设置为包括在内 它在每个控制器测试文件的before块中?

1 个答案:

答案 0 :(得分: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