Reputation: 1133
I'm writing some tests for a site that is protected with http authentication on all pages.
I've managed to come across a way of bypassing it for controller tests by doing the following
get exams_url, headers: {'HTTP_AUTHORIZATION' => ActionController::HttpAuthentication::Basic.encode_credentials('admin','admin') }
But how do I get past it for a system test? I've been searching around for hours to try and find a solution for this, but all of the suggestions I've found appear to be for older versions of Rails/Capybara and do not work. There doesn't appear to be anything in the Rails testing documentation regarding this either.
Upvotes: 1
Views: 664
Reputation: 501
There’s no need to mess with Capybara. Just add this method to ActiveSupport::TestCase
in your test_helper.rb
:
def visit_authenticated(url)
uri = URI.parse(url)
uri.user = 'put_your_user_here'
uri.password = 'put_your_password_here'
visit uri
end
Upvotes: 1
Reputation: 1133
Okay, this seems to do the trick for me
def visit_with_http_auth(path)
username = 'admin'
password = 'admin'
visit "http://#{username}:#{password}@#{Capybara.current_session.server.host}:#
{Capybara.current_session.server.port}#{path}"
end
And then in my test methods I just do
test "visiting the index" do
visit_with_http_auth questions_path
assert_selector "h1", text: "Questions"
end
Upvotes: 3