开发者

RSpec.configure and the request object

开发者 https://www.devze.com 2023-04-02 02:01 出处:网络
I have a Rails 3.1 application that is being built out as a RESTful API.The plan is to handle authentication based on an API key that is passed on each request via the Authorization HTTP header.In ord

I have a Rails 3.1 application that is being built out as a RESTful API. The plan is to handle authentication based on an API key that is passed on each request via the Authorization HTTP header. In order to test this in RSpec, I wanted to set the request.env["HTTP_AUTHORIZATION"] attribute in the config.before block:

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

Unfortunately, this throws an exception because the request object doesn't exist in the config.before block.

Is there another approach to setting this header outside of including it in the before block of each controller test file?


I haven't tried it myself but maybe creating shared examples group could help you to sort out your problem:

 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
0

精彩评论

暂无评论...
验证码 换一张
取 消