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)>
It is not necessary (although recommended) to put restrictions on the database.
The bug is in the test that fails when trying to create an extra instance of
Balance
(and finds that you already created one before).Grades
It would be nice if you shortened the code blocks a bit, so that the questions are more concise.
In these cases it is important to comment on the libraries you are using, in this case the error is in the use of shoulda which is not mentioned in the question.
Testing this type of detail is usually not necessary and even counterproductive, Rails has its own tests, it is not necessary to retest it.
Lastly, if you insist on testing this, it is convenient to persist the instances in the database (
FactoryGirl.create
) while it is enough to useFactoryGirl.build
which is much faster.Update
Shoulda doesn't work well when the uniqueness validation is on a
foreing_key
, because it tries to assign 'a' to it as a value .If you still want to do the test, you can do it by hand:
Likewise, doing this type of test is not recommended.