require 'rails_helper'

RSpec.describe Food, type: :model do

  describe 'validation' do

    it 'validates density' do
      i = build(:food)
      expect(i).to be_valid

      i.density = '5'
      expect(i).not_to be_valid

      i.density = '5 cup'
      expect(i).not_to be_valid

      i.density = '5 gram/cup'
      expect(i).to be_valid

      i.density = '5 mile/hour'
      expect(i).not_to be_valid

      i.density = '1 g/ml'
      expect(i).to be_valid
    end

  end

  describe 'set_usda_food' do
    it 'sets the density' do
      i = build(:food)
      f = create(:salted_butter)
      create(:usda_food_weight, usda_food: f)

      i.set_usda_food(f)

      expect(i.density).not_to be_nil
    end
  end

  describe '#custom_units' do
    it 'returns a hash based on food_units' do
      i = build(:food)
      i.food_units << FoodUnit.new(name: 'clove', gram_weight: 20.0)

      units = i.custom_units
      expect(units['clove']).to be_a UnitConversion::ValueUnit
      expect(units['clove'].value.value).to eq 20.0
      expect(units['clove'].unit.unit).to eq 'g'
    end
  end

  describe '#cache_key' do
    it 'has a key for new foods' do
      f = Food.new
      expect(f.cache_key).to eq "foods/new"
      expect(f.cache_version).to be_nil
    end
    
    it 'has a different key for new foods with an ndbn' do
      f = Food.new(ndbn: '123456')
      expect(f.cache_key).to eq "foods/new/123456"
      expect(f.cache_version).to be_nil
    end
    
    it 'has a key for persisted foods' do
      f = create(:food)
      expect(f.cache_key).to eq "foods/#{f.id}"
      expect(f.cache_version).not_to be_nil
    end
    
    it 'has the same key for persisted foods with an ndbn' do
      f = create(:food, ndbn: '123456')
      expect(f.cache_key).to eq "foods/#{f.id}"
      expect(f.cache_version).not_to be_nil
    end
  end
  
end
