ruby-on-railsrspec

Testing valid factory when belongs_to


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?


Solution

  • The whole shebang.

    Your tests should be testing the behavior of your application not your factories.

    If you want to sanity test that your factories produce valid records you do that through linting your factories. It's as easy as:

    FactoryBot.lint
    

    This step is often incorporated in bootstrapping your test suite.

    And also belongs_to adds a validation by default since Rails 5 came out in 2018. Your validation will actually both add an extra message in the errors and break the application in a subtile way as it will fail if the assocatiated record is not yet saved.