Testing rails "association"

589 views Asked by At

User has many profiles.

No issues with testing the parent. I'm stuck with testing its association.

The profile model is:

class Profile < ApplicationRecord
  belongs_to :user

  validates_presence_of :first_name, :last_name
end

And the profile_test file is:

require 'test_helper'

class ProfileTest < ActiveSupport::TestCase

  test "create profile" do
    profile = Profile.new({"first_name"=>"test", "last_name"=>"test"})
    assert profile.save
  end
end

When I run the test, it gets a Failure:

Minitest::Assertion: Expected false to be truthy.

Can anyone please make me clear why Create is not working?

1

There are 1 answers

0
Thanh On BEST ANSWER

In Rails 5, if belongs_to association is defined, it's required to have association record.

Your profile do not set a user, so profile.save returns false.