I am trying to prove that a foreign key is unique, since only one relationship can exist on that table per user.
My doubt is that I don't know if I have to put a restriction on the table indicating that the foreign field is also unique, or just placing the uniqueness validation in the ActiveRecord works.
My ActiveRecord
:
class Balance < ActiveRecord::Base
#association macros
belongs_to :user
belongs_to :wallet
#validation macros
validates :user_id, presence: true, uniqueness: true
validates :wallet_id, presence: true
end
My Factory
:
FactoryGirl.define do
factory :balance do
user
wallet
amount 2000
end
end
My quiz:
RSpec.describe Balance, type: :model do
let(:balance) { FactoryGirl.create :balance }
it "when is valid" do
expect(balance).to be_valid
end
it "when is presence user_id" do
expect(balance).to validate_presence_of :user_id
end
it "when is presence wallet_id" do
expect(balance).to validate_presence_of :wallet_id
end
it "when is uniqueness user_id" do
expect(balance).to validate_uniqueness_of :user_id #falla
end
it "when is belongs_to :user" do
should belong_to(:user)
end
it "when is belongs_to :wallet" do
should belong_to(:wallet)
end
end
Mistake
Balance when is uniqueness user_id
Failure/Error: let(:balance) { FactoryGirl.create :balance }
ActiveRecord::RecordInvalid:
Validation failed: User has already been taken
# ./spec/models/balance_spec.rb:5:in `block (2 levels) in <top (required)>'
# ./spec/models/balance_spec.rb:20:in `block (2 levels) in <top (required)>