require 'rails_helper'

RSpec.describe Recipe, type: :model do
  describe '#update_rating!' do

    it 'should set rating to nil with no ratings' do
      r = create(:recipe)
      r.update_rating!
      expect(r.rating).to be_nil

      create(:log, rating: nil, source_recipe: r)

      r.update_rating!
      expect(r.rating).to be_nil
    end

    it 'should set rating based on user logs' do
      user = create(:user)
      other_user = create(:user)
      r = create(:recipe, user: user)
      create(:log, rating: 2, source_recipe: r, user: user)
      create(:log, rating: 4, source_recipe: r, user: user)
      create(:log, rating: 5, source_recipe: r, user: other_user)

      r.update_rating!

      expect(r.rating).to eq 3
    end

  end

  describe '#tag_names' do

    it 'should return tag names' do
      t1 = create(:tag, name: 'one')
      t2 = create(:tag, name: 'two')

      r = create(:recipe)

      r.tags = [t1, t2]
      r.save

      expect(r.tag_names).to contain_exactly('one', 'two')
    end

    it 'should set existing tags' do
      t1 = create(:tag, name: 'one')
      t2 = create(:tag, name: 'two')

      r = create(:recipe)
      r.tag_names = ['one', 'two']
      expect(r.tags).to contain_exactly(t1, t2)
    end

    it 'should set new tags' do
      r = create(:recipe)
      r.tag_names = ['one', 'two']
      expect(r.tags.length).to eq 2
      expect(r.tags.first.persisted?).to be_truthy
    end

    it 'should set new and existing tags' do
      t1 = create(:tag, name: 'one')
      t2 = create(:tag, name: 'two')

      r = create(:recipe)
      r.tag_names = ['One', 'TWO', 'three']
      expect(r.tags).to include(t1, t2)
      expect(r.tags.length).to eq 3
      expect(r.tags.detect {|t| t.is?('THREE')}).not_to be_nil
    end

    it 'ignores empty elements' do
      r = create(:recipe)
      r.tag_names = ['one', 'two', nil, '']
      expect(r.tags.length).to eq 2
    end

  end
end
