require 'rails_helper'

RSpec.describe Invitation, type: :model do
  let(:user) { build :user }

  describe "tokens" do
    it "requires a user" do
      expect { Invitation.create! }.to raise_error(ActiveRecord::RecordInvalid)
    end

    it "generates a random token when created" do
      invitation = Invitation.new(user: user)
      invitation.save!
      token = invitation.token
      expect(token).to be_a(String)
      expect(token.length).to eq(16)

      invitation_2 = Invitation.create(user: user)
      expect(token).not_to eq(invitation_2.token)
    end
  end

  describe "scopes" do
    before do
      @unused_invitation = create :invitation, user: user
      @used_invitation   = create :invitation, user: user, used_at: DateTime.now
      @used_invitation_2 = create :invitation, user: user, used_at: DateTime.now
    end

    describe "#unused" do
      it "returns unused invitations" do
        expect(Invitation.unused.count).to eq(1)
        expect(Invitation.unused.first).to eq(@unused_invitation)
      end
    end

    describe "#used" do
      it "returns used invitations" do
        expect(Invitation.used.count).to eq(2)
        expect(Invitation.used.first).to eq(@used_invitation)
      end
    end
  end
end
