HTTP basic auth for Capybara

后端 未结 6 989
伪装坚强ぢ
伪装坚强ぢ 2020-12-05 00:06

I\'m writing some RSpec tests for my Rails 3 application and trying to switch from Webrat to Capybara. So far so good but the application uses HTTP basic auth to authorize m

6条回答
  •  一生所求
    2020-12-05 00:44

    Man, none of these solutions worked for me.

    Pistos' solution came close and worked for feature specs with js: true but failed when headless.

    This below solution works for me for both headless and js: true specs.

    spec/support/when_authenticated.rb

    RSpec.shared_context 'When authenticated' do
      background do
        authenticate
      end
    
      def authenticate
        if page.driver.browser.respond_to?(:authorize)
          # When headless
          page.driver.browser.authorize(username, password)
        else
          # When javascript test
          visit "http://#{username}:#{password}@#{host}:#{port}/"     
         end
      end
    
      def username
        # Your value here. Replace with string or config location
        Rails.application.secrets.http_auth_username
      end
    
      def password
        # Your value here. Replace with string or config location
        Rails.application.secrets.http_auth_password
      end
    
      def host
        Capybara.current_session.server.host
      end
    
      def port
        Capybara.current_session.server.port
      end
    end
    

    Then, in your spec:

    feature 'User does something' do
      include_context 'When authenticated'
    
      # test examples
    end
    

提交回复
热议问题