In my Rails application I have a model Profile
that belongs_to
a User
as such:
class User < ApplicationRecord
has_many :profiles
end
class Profile < ApplicationRecord
belongs_to :user
validates :user_id, presence: true
end
The factory for Profile is as follows:
FactoryBot.define do
factory :profile do
sequence(:name) { |n| "Profile #{n}" }
association :user
end
end
Now this test in the model tests is failing:
it 'should have a valid factory' do
expect(build(:profile)).to be_valid
end
Here I'm not sure which part is wrong. Is it testing for the presence for user_id
. Should the validator be different? OR should I be creating a user before the profile. Which does not seem right as well, since then its a wrong test, because the factory should be doing this.
What am I doing wrong?
validates :user_id, presence: true
is totally unnecessary, belongs do all things 2) in factory you can simply writeuser
instead ofassociation :user
belongs_to
default association validations were added in Rails 5, so if you are not receiving an error I have to assume you are on < 5belongs_to :user
then when you try to save Profile without user -> you will get error (so additional validation is not required)