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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With