Created
December 13, 2011 02:24
-
-
Save jrep/1470172 to your computer and use it in GitHub Desktop.
Rspec and HTTP_AUTHORIZATION
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# I'm trying to add HTTP BasicAuth to an existing Rails API (not app - no pages or views). | |
# | |
# At http://blog.matthodan.com/how-to-test-something-with-rspec | |
# (and a thousand or so other places) | |
# I find that it's easy to test this: | |
describe SourcesController do | |
describe "#index" do | |
before :each do | |
@request.env['HTTP_AUTHORIZATION'] | |
= "Basic #{ActiveSupport::Base64::encode64('user:secret')}" | |
end | |
it "should have this action" do | |
… | |
# Which sounds just swell, guys, but I get | |
Failure/Error: @request.env['HTTP_AUTHORIZATION'] = "Basic #{ActiveSupport::Base64::encode64('user:secret')}" | |
NoMethodError: | |
undefined method `env' for nil:NilClass | |
# ./spec/integration/xxxx/subscriptions_spec.rb:14:in `block (3 levels) in <top (required)>' | |
# so, apparently @request is nil. I tried "request" as well, same result. | |
# perhaps there's been some massive reorganization of the RSPEC test case classes? | |
# pp self.class.ancestors, as of the line before the unhappy nil, is | |
[RSpec::Core::ExampleGroup::Nested_6::Nested_1, | |
RSpec::Core::ExampleGroup::Nested_6] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
No, ENV didn't do it for me. Here's what did:
In spec/controllers/resource.rb:
require 'integration'
describe ResourceController do
include BasicAuthHelper
before do
http_login(organization, user, pw)
end
…
end
in spec/support/integration.rb:
module BasicAuthHelper
def http_login(organization, user, pw)
request.env['HTTP_AUTHORIZATION'] = ActionController::HttpAuthentication::Basic.encode_credentials(user,pw)
end
end
That is, inventing a top-level module BasicAuthHelper, in order to get the namespaces right, seemed to be the trick.