0
votes

I can't create a valid comment factory using factory girl. My comment model belongs to commentable and is polymorphic. I've tried a whole bunch of different things, but at the moment, most of my tests are failing with this error:

ActiveRecord::RecordInvalid:
    Validation failed: User can't be blank, Outlet can't be blank

I'm not sure why it isn't passing validation, especially because my comment model validates the presence of user_id and outlet_id, not User and Outlet

Here is my factory:

factory :comment do
    body "This is a comment"
    association :outlet_id, factory: :outlet
    association :user_id, factory: :user
    #outlet_id factory: :outlet
    association :commentable, factory: :outlet
end

class CommentsController < ApplicationController

def new
    @comment = Comment.new
end

def create
    @outlet = Outlet.find(params[:outlet_id])
    @comment = @outlet.comments.build(comment_params)
    @comment.user_id = User.find(params[:user_id]).id


    if @comment.save
        redirect_to(@outlet)
    end
end

def edit
    @comment = Comment.find(params[:id])
end

def update
    @comment = Comment.find(params[:id])

    if @comment.update(comment_params)
        redirect_to @comment.outlet
    end
end

def destroy
    @comment = Comment.find(params[:id])

    if @comment.destroy
        redirect_to @comment.outlet
    end
end


private
def comment_params
    params.require(:comment).permit(:body, :outlet_id, :user_id)
end

end


class Comment < ApplicationRecord
   belongs_to :commentable, polymorphic: true

   validates :body, :user_id, :outlet_id, presence: true
   validates :body, length: { in: 1..1000 }
end

1
what happens if you remove the validation validates :user_id, :outlet_id, presence: true ?Fredius
the test will pass, but i feel like I should be validating that each comment has a user_id and outlet_id that it belongs to, no?Harry B.
yup, but i don't understand why don't you use the models instead of the idsFredius
When I change the validation to user and outlet then the error I get for why I don't have a valid factory is: NoMethodError: undefined method `user' for #<Comment:0x007f9a7e45b058> Did you mean? user_idHarry B.
but you should define the association in the the model Comment first, like you do with commentableFredius

1 Answers

0
votes

Is there a particular reason for using association :user_id?

You probably want something more like:

factory :comment do
    body "This is a comment"
    association :outlet, factory: :outlet
    association :user, factory: :user
    association :commentable, factory: :outlet
end

Which incidentally can simplify to:

factory :comment do
    body "This is a comment"
    outlet
    user
    association :commentable, factory: :outlet
end