Skip to content

Instantly share code, notes, and snippets.

@enricostano
Last active December 28, 2015 14:19
Show Gist options
  • Save enricostano/7513773 to your computer and use it in GitHub Desktop.
Save enricostano/7513773 to your computer and use it in GitHub Desktop.
class ApiKey < ActiveRecord::Base
after_initialize do
:generate_access_token unless access_token?
end
belongs_to :user
validates :access_token, :user,
presence: true
validates :access_token,
uniqueness: true
private
def generate_access_token
begin
self.access_token = SecureRandom.hex
end while self.class.exists?(access_token: access_token)
end
end
require 'spec_helper'
describe ApiKey do
describe "Validations" do
it "should have valid factory" do
expect(FactoryGirl.build(:api_key)).to be_valid
end
it { should validate_presence_of(:access_token) }
it { should validate_presence_of(:user) }
it { FactoryGirl.create :api_key
should validate_uniqueness_of(:access_token) }
end
describe "Associations" do
it { should belong_to(:user) }
end
it "generates access token before validation" do
allow(SecureRandom).to receive(:hex).and_return 'foobar'
api_key = FactoryGirl.build :api_key
expect{ api_key.valid? }.to change{ api_key.access_token}.to 'foobar'
end
end
class User < ActiveRecord::Base
has_secure_password
has_one :profile,
as: :profilable
has_many :waiting_list_memberships,
dependent: :destroy
has_many :users_unit_memberships,
dependent: :destroy
has_many :users_units,
through: :users_unit_memberships
has_many :groups,
through: :users_units
has_many :waiting_groups,
through: :waiting_list_memberships,
source: :group
has_many :api_keys,
dependent: :destroy
validates :name,
presence: true
validates :email,
presence: true,
uniqueness: true
def session_api_key
api_keys.first_or_create
end
end
@cupakromer
Copy link

context "generating a new key" do
  it "sets a token by default" do
    allow(SecureRandom).to receive(:hex).and_return('testkey')
    expect(ApiKey.new.access_token).to eq 'testkey'
  end

  it "sets a token if it is nil" do
    allow(SecureRandom).to receive(:hex).and_return('testkey')
    expect(ApiKey.new(access_token: nil).access_token).to eq 'testkey'
  end

  it "uses a token if present" do
    expect(ApiKey.new(access_token: 'provided').access_token).to eq 'provided'
  end

  it "sets a unique token" do
    FactoryGirl.create :api_key, access_token: 'taken'
    keys = %w[ taken another ]

    allow(SecureRandom).to receive(:hex) { keys.shift }

    expect(ApiKey.new.access_token).to eq 'another'
  end
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment