Monday, May 23, 2011

Rails 3 - Testing Authentication (format html and xml)

Hey guys,

This is a brief post showing you some functional test examples that test site authentication. I'm testing both format:html (via sessions), and format:xml (via HTTP Basic Auth).


Format HTML tests (session authorization):

test "should show user's account when logged in" do
    get :account, { :id => @user.to_param }, { :user => @user.to_param }
    assert_response :success
end

test "shouldn't show user's account when not logged in" do
    get :account, { :id => @user.to_param }
    assert_redirected_to new_session_path
end

test "shouldn't get edit as logged in as different user" do
    get :edit, { :id => @other_user.to_param }, { :user => @user.to_param }
    assert_redirected_to user_path(@other_user)
end


Format XML Tests (http_auth authorization):

test "shouldn't show account (xml) without http_auth provided" do
    get :account, { :format => 'xml', :id => @user.to_param }, { :user => @user.to_param }
    assert_response :unauthorized
end

test "should show account (xml) with http_auth provided"  do
    @request.env['HTTP_AUTHORIZATION'] = encode_credentials(@user.user_name, password_for(@user))
    get :account, { :format => 'xml', :id => @user.to_param }
    assert_response :success
end

test "shouldn't show account (xml) with bad http_auth provided"  do
    @request.env['HTTP_AUTHORIZATION'] = encode_credentials('foo', 'bar')
    get :account, { :format => 'xml', :id => @user.to_param }
    assert_response :unauthorized
  end

N.B.
Assumes that in your test helper files you have a password_for(user) method.

Assumes the following test setup:
setup do
    @user = users(:joe)
    @other_user = users(:jane)
end

No comments: