rspecrspec-rails

Rspec testing for comment model ( Validation failed: User must exist)


I have a association for comment and the user model ( belongs_to :user and has_many :comments). in the comment_spec it throwing an error. comment model:

class Comment < ApplicationRecord
belongs_to :post
belongs_to :user
validates :post_id, presence: true
validates :body, presence:true, length: {minimum: 4}
end

Posts model

class Post < ApplicationRecord
validates :title, presence: true, length: {minimum: 3}
validates :body, presence: true
has_many :comments, dependent: :destroy
belongs_to :user
accepts_nested_attributes_for :ratings
end

User model

class User < ApplicationRecord
devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable
has_many :posts
has_many :comments
end

Factories for comment

FactoryBot.define do
factory :comment do
body "sdfs dfjsdbf dsbfs"
post {create(:post)}
user_id {create (:user)}
end
end

Factories for users

require 'faker'
FactoryBot.define do
factory :user do
email {Faker::Internet.email}
password "123456"
end
end

Comment model spec

  require 'rails_helper'
  RSpec.describe Comment, type: :model do
  describe "validations" do
  describe "it is not present" do
  let(:comment) {build(:comment,body:'')}
  it 'should be invalid' do
    expect(comment.valid?).to be_falsey
  end
end

describe "it does not have minimum 3 char" do
  let(:comment) {build(:comment,body:'12')}
  it 'should be invalid' do
    expect(comment.valid?).to be_falsey
  end
end
end

 describe "It is under a post" do
 let(:comment) {build(:comment)}
 it "it belongs to a post " do
   expect(comment.post).to be_truthy
 end
end
end

when i test the above comment model it showing the error Failure/Error: post {create(:post, user: user)}

 ActiveRecord::RecordInvalid:
   Validation failed: User must exist

Solution

  • Redefine your comment factory as

    FactoryBot.define do
      factory :comment do
        body "sdfs dfjsdbf dsbfs"
        post
        user
      end
    end
    

    In your comment_spec.rb

    user = create :user
    comment = create :comment, user: user