Mind Dump, Tech And Life Blog
written by Ivan Alenko
published under license Attribution-ShareAlike 4.0 International (CC BY-SA 4.0)copy! share!
posted at 10. Aug '23

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:

Add Comment