require 'spec_helper'

describe User do
  before(:each) do
    @user = User.new
  end

  it "should not be valid by default" do
    @user.should_not be_valid
  end

  it "should be valid after setting correct attributes" do
    @user.update_attributes({
      :username => 'bart',
      :email => 'bart@simpsons.com',
      :password => 'kwyjibo',
      :password_confirmation => 'kwyjibo' })
    @user.should be_valid
  end

  context "with shopping lists" do
    before(:each) do
      @sl1 = Factory.create(:shopping_list)
      @sl2 = Factory.create(:shopping_list)
      
      @items = []
      @items[0] = Factory.build(:item1)
      @items[1] = Factory.build(:item2)
      @items[2] = Factory.build(:item3)
      @items[0].update_attribute(:cost, 3.29)
      @items[1].update_attribute(:cost, 2.39)
      @items[2].update_attribute(:cost, 85.99)
      
      [0,1].each { |item| @sl1.items << @items[item] }
      @sl2.items << @items[2]
    end

    it "should properly calculate totals with only one shopping list" do
      @user.shopping_lists << @sl1
      
      @user.shopping_list_totals.should == 5.68
      @user.total_cost_bought.should == 0
      @user.total_cost_remaining.should == 5.68
      @sl1.items.first.purchase
      @user.shopping_list_totals.should == 5.68
      @user.total_cost_bought.should == 3.29
      @user.total_cost_remaining.should == 2.39
      @sl1.items.last.purchase
      @user.shopping_list_totals.should == 5.68
      @user.total_cost_bought.should == 5.68
      @user.total_cost_remaining.should == 0
    end

    it "should properly calculate totals with two shopping lists combined" do
      @user.shopping_lists << @sl1
      @user.shopping_lists << @sl2
      @user.shopping_list_totals.should be_within(0.0001).of(91.67)
      
      @user.shopping_lists.first.items.first.purchase
      
      @user.shopping_list_totals.should be_within(0.0001).of(91.67)
      @user.total_cost_bought.should == 3.29
      @user.total_cost_remaining.should == 88.38
    end
  end
end
