diff --git a/app/models/api_key.rb b/app/models/api_key.rb index 9145ce4372e..a617902d41f 100644 --- a/app/models/api_key.rb +++ b/app/models/api_key.rb @@ -2,6 +2,7 @@ class ApiKey < ActiveRecord::Base belongs_to :user belongs_to :created_by, class_name: User + validates :user_id, uniqueness: true validates_presence_of :key def regenerate!(updated_by) diff --git a/spec/models/api_key_spec.rb b/spec/models/api_key_spec.rb index 5d163dc368d..5196c16eb50 100644 --- a/spec/models/api_key_spec.rb +++ b/spec/models/api_key_spec.rb @@ -3,14 +3,18 @@ require 'rails_helper' require_dependency 'api_key' describe ApiKey do + let(:user) { Fabricate(:user) } + it { is_expected.to belong_to :user } it { is_expected.to belong_to :created_by } - it { is_expected.to validate_presence_of :key } - skip 'validates uniqueness of user_id' do - Fabricate(:api_key) - is_expected.to validate_uniqueness_of(:user_id) + it 'validates uniqueness of user_id' do + Fabricate(:api_key, user: user) + api_key = Fabricate.build(:api_key, user: user) + + expect(api_key.save).to eq(false) + expect(api_key.errors).to include(:user_id) end end