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 my admin user, any idea how I can test that with Capybara?
Here is my current Webrat step:
it 'should authenticate for admin' do basic_auth('user', 'secret') visit '/admin' response.status.should eql 200 response.status.should_not eql 401 end
How do I do this with Capybara? Thanks!
HTTP basic authentication is a simple challenge and response mechanism with which a server can request authentication information (a user ID and password) from a client. The client passes the authentication information to the server in an Authorization header. The authentication information is in base-64 encoding.
HTTP Basic Auth is a simple method that creates a username and password style authentication for HTTP requests. This technique uses a header called Authorization, with a base64 encoded representation of the username and password.
Because basic authentication does not encrypt user credentials, it is important that traffic always be sent over an encrypted SSL session. A user authenticating with basic authentication must provide a valid username and password.
With Basic Authentication, you pass your credentials (your Apigee account's email address and password) in each request to the Edge API. Basic Authentication is the least secure of the supported authentication mechanisms. Your credentials are not encrypted or hashed; they are Base64-encoded only.
I got it to work using page.driver.basic_authorize(name, password)
instead
Update:
At the moment, after a Capybara upgrade, I'm using this pile of workarounds:
if page.driver.respond_to?(:basic_auth) page.driver.basic_auth(name, password) elsif page.driver.respond_to?(:basic_authorize) page.driver.basic_authorize(name, password) elsif page.driver.respond_to?(:browser) && page.driver.browser.respond_to?(:basic_authorize) page.driver.browser.basic_authorize(name, password) else raise "I don't know how to log in!" end
The default Capybara driver, rack-test, has a basic_authorize
method (with alias authorize
) for Basic HTTP Auth, and digest_authorize
for Digest HTTP Auth, here you can find them: https://github.com/brynary/rack-test/blob/master/lib/rack/test.rb
So you can do:
page.driver.browser.authorize 'login', 'password'
Or you can write a simple helper for Basic HTTP Auth:
def basic_auth(user, password) encoded_login = ["#{user}:#{password}"].pack("m*") page.driver.header 'Authorization', "Basic #{encoded_login}" end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With