While I was trying to cover a controller with some tests I faced a problem. The controller actions where protected by a filter that prompted the users for login via basic http authentication.

I found a solution in rails code here http://github.com/rails/rails/tree/master/actionpack/lib/action_controller/http_authentication.rb where it said you should do your get as follows

get("/notes", nil, :authorization =>
ActionController::HttpAuthentication::Basic.encode_credentials(users(:x).name, users(:x).password))

This didn’t work for me where basic http authentication required sending the encoded credentials in the request headers while the previous get request sent the authorization credentials in the session.

I found the following code snippet in http://snippets.dzone.com/posts/show/3785 which allowed me to set request headers

class ActionController::TestRequest
def set_header(name, value)
@env[name] = value
end
end

In my tests, I now write the following

@request.set_header "HTTP_AUTHORIZATION", ActionController::HttpAuthentication::Basic.encode_credentials(users(:x).email, '0000')
get :show, {:user_id => users(:x).id, :format => "rss"}

And it works like a charm !

About these ads