Howto Login With Basic Auth In System Spec
The difference of my helper to those on stackoverflow is that it works (for system specs) and can “login” into basic auth dialogue, but actually it just modifies URL.
The answers on stackoverflow use host
, page.driver.host
and similar. page.driver.host
is not defined in selenium web driver, host
is www.example.com which is wrong. The correct path is page.server_url
which points to out local puma test server.
It is crazy I had to go through public_methods
of a page
object to dig something out.
Let’s do it:
Create helper module in spec/support/system_helpers.rb
, be sure it is required in spec/rails_helper.rb
(Dir[Rails.root.join('spec', 'support', '**', '*.rb')].each { |f| require f }
).
module SystemHelpers
def visit_with_basic_auth(path, username, password)
uri = Addressable::URI.parse(page.server_url)
uri.user = username
uri.password = password
uri.path = path
visit(uri.to_s)
end
end
Include the module to system specs:
RSpec.configure do |config|
...
config.include SystemHelpers, type: :system
...
end
Then use visit_with_basic_auth
instead of visit
for the first visit
:
require "rails_helper"
RSpec.describe "my feature", type: :system do
it 'lists stuff' do
visit_with_basic_auth(admin_stuff_path, ENV['ADMINISTRATION_USER'], ENV['ADMINISTRATION_PASSWORD'])
expect(page).to have_css('h1', text: 'Admin Stuff')
object = create(:object, name: 'foo')
visit admin_stuff_path
within '.my-namespace' do
expect(page).to have_css('.stuff-object-name', text: 'foo')
end
end
end
And that’s all.
See also:
- for Rack::Test - https://gist.github.com/alishutc/2044085
- seems to be created for classic feature tests with
js: true
- https://stackoverflow.com/questions/4329985/http-basic-auth-for-capybara - for me
page.driver.header
does not work, but it’s from 2014… - https://github.com/thoughtbot/capybara-webkit/issues/69
Add Comment