require 'rails_helper'

RSpec.describe ApiKey, type: :model do
  let!(:user) { FactoryGirl.create(:user) }
  before do
    @token = ApiKey.new(access_token: 'token', expires_at: Time.current, user_id: user.id)
  end

  subject { @token }
  it { should respond_to(:access_token) }
  it { should respond_to(:expires_at) }
  it { should respond_to(:user_id) }
  it { should respond_to(:user) }

  it { should be_valid }

  describe "when user_id is not present" do
    before { @token.user_id = nil }
    it { should_not be_valid }
  end

  describe "when user_id is less than zero" do
    before { @token.user_id = -1 }
    it { should_not be_valid }
  end

  describe "when expires_at is before now" do
    before { @token.expires_at = Time.current - 1.day }
    specify { expect(@token.expired?).to be_truthy }
  end

  describe "when expires_at is after now" do
    before { @token.expires_at = Time.current + 1.day }
    specify { expect(@token.expired?).to be_falsey }
  end

  describe "when token saved" do
    before do 
      Timecop.freeze(Time.zone.local(2015,11,11))
      @token.save 
    end
    after do
      Timecop.return
    end
    let(:found_token) { ApiKey.find_by(access_token: @token.access_token) }

    specify { expect(found_token.expires_at).to eq Time.zone.local(2015,11,11) + 30.day }
    specify { expect(found_token.access_token).not_to be_nil }
  end
end
