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

class GroupsController; def rescue_action(e) raise e end; end

class GroupsControllerTest < Test::Unit::TestCase
  main_scenario

  def setup
    @controller = GroupsController.new
    @request    = ActionController::TestRequest.new
    @response   = ActionController::TestResponse.new
    @request.session[:user_id] = 1000001

    @first_id = groups(:first_group).id
  end

  def test_index
    get :index
    assert_response :success
    assert_template 'list'
  end

  def test_list
    get :list

    assert_response :success
    assert_template 'list'

    assert_not_nil assigns(:groups)
  end

  def test_new
    get :new

    assert_response :success
    assert_template 'new'

    assert_not_nil assigns(:group)
  end

  def test_create
    num_groups = Group.count

    post :create, :group => {:name => 'New Group'}

    assert_response :redirect
    assert_redirected_to :action => 'list'

    assert_equal num_groups + 1, Group.count
  end

  def test_edit
    get :edit, :id => @first_id

    assert_response :success
    assert_template 'edit'

    assert_not_nil assigns(:group)
    assert assigns(:group).valid?
    assert_not_nil assigns(:users)
  end

  def test_update
    post :update, :id => @first_id
    assert_response :redirect
    assert_redirected_to :action => :edit, :id => @first_id
  end

  def test_update_with_detour
    add_stored_detour
    
    post :update, :id => @first_id

    assert_response :redirect
    assert_redirected_to :controller => 'bogus', :action => :location

    assert_not_nil assigns(:group)
    assert assigns(:group).valid?
  end

  def test_destroy
    assert_nothing_raised {
      Group.find(@first_id)
    }

    post :destroy, :id => @first_id
    assert_response :redirect
    assert_redirected_to :action => 'list'

    assert_raise(ActiveRecord::RecordNotFound) {
      Group.find(@first_id)
    }
  end
  
  def test_set_member
    long_user = users(:long_user)
    assert groups(:first_group).users.size == 1
    
    post :set_member, :id => @first_id, :user_id => long_user.id, :value => 'true'

    assert groups(:first_group).users.include?(users(:tesla))
    assert groups(:first_group).users.include?(users(:long_user))
  end
  
  private

  # TODO (uwe): This method should be removed
  # It is here only because ClassTableInheritanceInRails broke  reading fixtures by name
  def users(login)
    User.find(:first, :conditions => "login = '#{login.to_s}'")
  end  

  # TODO (uwe): This method should be removed
  # It is here only because ClassTableInheritanceInRails broke  reading fixtures by name
  def groups(name)
    Group.find(:first, :conditions => "name = '#{name.to_s}'")
  end
  
end