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

class LibraryControllerTest < Test::Rails::ControllerTestCase

  fixtures :topics, :users, :settings, :support_materials, :readings
  
  def setup
    super
    login_as :laura
  end
  
  def test_remove_kills_dependent_readings
    assert_difference(Reading, :count, '', -1) do
      post :remove, :id => 2
    end    
  end
    
  # only admin can access the actions other than index
  def test_redirect_participant
    login_as :ernest # a participant
    [:new, :edit, :remove].each do |action| 
      get action
      assert_response :redirect
    end
  end
  
  def test_all_can_access_index
    [:laura, :frank, :ernest].each do |user|
      login_as user
      get :index
      assert_response :success
    end
  end
  
  def test_id_required
    login_as :laura # an admin
    [:new, :edit, :remove].each do |action| 
      get action
      assert_response :redirect
      assert flash[:alert]
    end
  end

  [[:frank, Expert], [:laura, Admin]].each do |user, klass|
    [:new, :edit].each do |action|  # successfull remove would be a redirect anyways
      define_method("test_#{klass}_can_access_#{action}") do
        login_as user
        get action, :id => 1
        assert_response :success
      end    
    end
  end
    
  def test_show_new
    get :new, :id => 1
    assert_response :success
    assert_assigned :support_material
    assert_equal 1, assigns(:support_material).topic_id
  end
  
  def test_create_creates
    assert_difference(SupportMaterial, :count) do
      post_new
    end
  end

  def test_create_set_flash
    post_new
    assert flash[:notice]
  end

  def test_create_redirects
    post_new
    assert_response :redirect
  end
  
  def test_when_failing_create_renders
    post_new(nil, '')
    assert_response :success
  end
  
  def test_when_failing_create_assigns_support_material
    post_new(nil, '')
    assert_assigned :support_material
  end
  
  def test_breadcrumb_index
    get :index
    assert_assigned :breadcrumb_trail
    assert_equal "Library", assigns(:breadcrumb_trail)[-1]
  end
  
  def test_breadcrumb_edit
    get :edit, :id => 1
    assert_assigned :breadcrumb_trail
    assert_equal "Edit", assigns(:breadcrumb_trail).pop
    assert_equal "Library", assigns(:breadcrumb_trail).pop.first
  end
  
  def test_remove_when_file_not_found
    SupportMaterial.any_instance.expects(:destroy).raises(TypeError)
    assert_nothing_raised() { post :remove, :id => 5 }
    assert_equal "There was a problem removing that Support Matrial", flash[:alert]
  end
  
 private
  
  def post_new(file = nil, name = nil)
    post :new, :id => 1, :support_material =>{
      :uploaded_data => file || fixture_file_upload('files/voted2006.html', 'text/html'),
      :name => name || 'Votes 2006'}    
  end
end
