require 'rails_helper'

describe Dunlop::UsersController, type: :controller, broken: Rails.version.starts_with?('4') do
  routes { Dunlop::Engine.routes }
  before { sign_in user }

  context "without abilities" do
    let(:user) { create :user, role_names: [], role_names_admin: [] }

    it "cannot add abilities through update_profile" do
      patch :update_profile, params: {user: {role_names: ['my-hackery-UserRole'], role_names_admin: ['my-hackery-UserAdminRole']}}
      user.reload.role_names.should be_empty
      user.role_names_admin.should be_empty
    end

    it "cannot add abilities through personal route by id" do
      patch :update, params: {id: user.id, user: {role_names: ['my-hackery-UserRole'], role_names_admin: ['my-hackery-UserAdminRole']}}
      user.reload.role_names.should be_empty
      user.role_names_admin.should be_empty
    end

    it "cannot list users" do
      get :index
      response.status.should eq 403
    end

    it "cannot show/edit other user" do
      other_user = create :user, role_names: [], role_names_admin: []
      get :show, params: {id: other_user.id}
      response.status.should eq 403
      get :edit, params: {id: other_user.id}
      response.status.should eq 403
    end
  end

  context "with user manage abilities (try to add admin rights mwha mwha mwha)" do
    let(:user) { create :user, role_names_admin: ['manage-class-User'] }

    it "cannot set other admin roles" do
      patch :update, params: {id: user.id, user: {role_names: ['my-added-UserRole'], role_names_admin: ['my-hackery-UserAdminRole']}}
      user.reload.role_names.should eq ['my-added-UserRole']
      user.role_names_admin.should  eq ['manage-class-User'] # set in other way
    end

    it "can edit other user's role_names, but not role_names_admin" do
      other_user = create :user, role_names: [], role_names_admin: []
      patch :update, params: {id: other_user.id, user: {role_names: ['my-added-UserRole'], role_names_admin: ['my-hackery-UserAdminRole']}}
      other_user.reload.role_names.should eq ['my-added-UserRole']
      other_user.role_names_admin.should be_empty
    end
  end

end


