require 'spec_helper'

describe SupplierEmployeesSettings do
  let(:supplier){ build :supplier }
  let(:employee){ create :employee}
  subject {supplier.settings_for(employee)}
  before do
    supplier.add_employee employee
    employee.enrich_with_settings supplier.settings_for(employee)
  end


  context "Settings" do

    describe "method inferring" do

      it "regognizes booleans with questionmarks" do
        subject.is_manager?.should be false
      end

    end
  end

  describe "boolean setting" do
    it "sets the value with exclamation mark with is_ prefix" do
      subject.manager.should be false
      subject.is_manager!
      subject.manager.should be true
    end

    it "sets the value with exclamation mark" do
      subject.manager.should be false
      subject.manager!
      subject.manager.should be true
    end
  end

  context "Employee context" do
    it 'responds to defaults without full initialization (yes this test is needed)' do
      Employee.new.manager?.should be false
    end

    it 'responds to defaults' do
      employee.manager?.should be false
      employee.active?.should be true
      employee.color.should == '#3a87ad'
    end

    it 'Sets the values non persisted on the supplier' do
      employee.manager = true
      supplier.employee_settings_storage[employee.id]['manager'].should be true
      supplier.reload
      supplier.employee_settings_storage.should_not be_present
    end

    it 'persists settings of the supplier on save' do
      employee.manager = true
      employee.save
      supplier.reload
      supplier.employee_settings_storage[employee.id]['manager'].should be true
    end

    it 'does not non existant suppliers on save' do
      employee.manager = true
      ->{ employee.save }.should_not change{ Supplier.count }
    end

    it 'sets attributes on the employee if fetched through the supplier' do
      settings = supplier.settings_for employee
      settings.is_manager!
      employee.manager?.should be true
    end

    it 'Implements settings on employees' do
      supplier.update employee_settings_storage: {employee.id => { 'manager' => true }}
      supplier.reload
      # Without the acessor employees on the supplier, the employee and therefore its settings are not linked to the supplier
      linked_employee = supplier.employees.find{|e| e.id == employee.id }
      linked_employee.should be_manager
    end
  end
end
