-
-
Save jrep/1470172 to your computer and use it in GitHub Desktop.
# 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] |
Another, similar, bloggage puts the request.env[] voodoo between the two "describe" levels. self.class.ancestors at that point is:
[Class,
Module,
ActiveSupport::Dependencies::ModuleConstMissing,
Object,
PP::ObjectMixin,
ActiveSupport::Dependencies::Loadable,
FactoryGirl::Syntax::Vintage,
Nori::CoreExt::Object,
Wasabi::CoreExt::Object,
JSON::Ext::Generator::GeneratorMethods::Object,
RSpec::Core::SharedExampleGroup,
RSpec::Core::DSL,
Kernel,
BasicObject]
… but I get the same "undefined method `env' for nil:NilClass" failure
It's been suggested to me that "request.env" is now spelled "ENV".
Hi @jrep, I'm facing the same issue in my tests when running with the saucelabs gem, about ENV did it work for you?
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.
Oh, also possibly useful: