require File.dirname(__FILE__) + '/../test_helper'

class AvatarsControllerTest < Test::Rails::ControllerTestCase

  fixtures :users, :avatars
  
  def setup
    super
    login_as :arthur # arthur has no avatar yet
    ApplicationPolicy.stubs(:participation_enabled?).returns(true)
  end
  
  def test_new_creates_avatar_for_current_user
    get :new
    
    assert_response :success
    assert_assigned :avatar
    assert_equal users(:arthur), assigns(:avatar).user
  end  
  
  def test_new_creates_avatar_does_not_destroy_current
    login_as :quentin
    quentin = users(:quentin)
    original_avatar_id = quentin.avatar.id
    get :new
    
    assert_response :success

    assert_equal original_avatar_id, quentin.avatar.reload.id
  end  
  
  def test_get_create_renders_new
    get :create
    
    assert_response :success
    assert_template 'new'    
  end
  
  def test_guests_cannot_access_new
    @request.session[:user] = nil

    get :new

    assert_response :redirect
  end
  
  def test_guests_cannot_access_create
    @request.session[:user] = nil

    post :create

    assert_response :redirect
  end
  
  def test_post_create_success_creates_avatar
    assert_difference(Avatar, :count, '', 2) do # one full-size, one thumbnail
      post_create
    end
  end
  
  def test_post_create_success_shows_avatar_page
    post_create
    assert_response :success
    assert_template 'new'    
  end
  
  def test_post_create_fails_with_non_graphic
    assert_no_difference(Avatar, :count) do
      post_create(fixture_file_upload('files/voted2006.html', 'text/html'))
    end
    assert_response :success
  end
  
  def test_remove
    assert_difference(Avatar, :count, '', -2) do # one full-size, one thumbnail
      login_as :quentin
      get :remove
    end
  end
  
  private
  
  def post_create(file = nil)
    post :create, :avatar =>{
      :uploaded_data => file || fixture_file_upload('files/AA_pirate!.jpg', 'image/jpeg'),
      }    
  end
  
end
