require 'spec_helper'
require 'spec_slugs_helper'

describe 'Slug Helpers' do

  describe "Eligibility" do

    it 'can determine sluggable base class' do
      expect(SlugHelpers.base_sluggable_class?(Resource)).to be_truthy
    end

    it 'can determine non-sluggable base class' do
      expect(SlugHelpers.base_sluggable_class?(TopContainer)).to be_falsey
    end

  end

  describe "Generate" do

    let(:slug_prefix) { 'slugtest' }

    it 'defaults to job not running' do
      expect(SlugHelpers.job_running?).to be_falsey
    end

    it 'primes the cache when job running' do
      slug = slug_prefix + rand(1000000).to_s
      resource_with_slug(slug, false)
      SlugHelpers.job_running(status: true)
      expect(SlugHelpers.job_running?).to be_truthy
      expect(SlugHelpers.cache.count).to eq 1
      expect(SlugHelpers.slug_in_use?(slug)).to be_truthy
    end

    it 'resets the cache when job complete' do
      slug = slug_prefix + rand(1000000).to_s
      resource_with_slug(slug, false)
      SlugHelpers.job_running(status: true)
      SlugHelpers.job_running(status: false)
      expect(SlugHelpers.job_running?).to be_falsey
      expect(SlugHelpers.cache.count).to eq 0
      expect(SlugHelpers.slug_in_use?(slug)).to be_truthy
    end

    it 'resets autogenerated slugs' do
      slug = slug_prefix + rand(1000000).to_s
      r = resource_with_slug(slug, true)
      SlugHelpers.job_running(status: false)

      r = Resource.find(id: r.id)

      expect(r[:slug]).to eq(slug)
      expect(r[:is_slug_auto]).to eq(1)
      expect(SlugHelpers.slug_in_use?(slug)).to be_truthy

      SlugHelpers.reset_autogenerated_slugs
      r = Resource.find(id: r.id)
      expect(r[:slug]).to be_nil
      expect(r[:is_slug_auto]).to eq(1)
      expect(SlugHelpers.slug_in_use?(slug)).to be_falsey
    end

  end

end
