Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RSpec.configure and the request object

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_transactional_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?

like image 870
Hector Castro Avatar asked Sep 01 '11 22:09

Hector Castro


1 Answers

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
like image 170
iafonov Avatar answered Oct 20 '22 04:10

iafonov