How to identify a polymorphic relationship with a factory girl

I have custom and story models that have comments.

I announced the following models as shown below:

class Comment
  belongs_to :commentable, polymorphic: true
  belongs_to :user
end

class User
end

class Story
end

Now I want to declare a comment object with FactoryGirl, which belongs to the same user who deserves praise and as a user.

Here is my code:

FactoryGirl.define do
  factory :user do
    sequence(:email) {|n| "person#{n}@exmaple.com"}
    sequence(:slug) {|n| "person#{n}"}
  end

  factory :comment do    
    occured_at { 5.hours.ago }
    user
    association :commentable, factory: :user
  end

end

The problem is that the user who writes the comment and the commendable user is not the same.

Why should I fix this?

Many TNX

+5
source share
2 answers

First of all, I don’t think you have already set up your associations ... I think this is what you want:

class Comment < AR
  belongs_to :commentable, polymorphic: true
end

class User < AR
  has_many :comments, as: :commentable
end

class Story < AR
  has_many :comments, as: :commentable
end

See: http://guides.rubyonrails.org/association_basics.html#polymorphic-associations

.

-, Factory , . :

FactoryGirl.define do
  factory :user do
    sequence(:email) {|n| "person#{n}@exmaple.com"}
    sequence(:slug) {|n| "person#{n}"}
  end

  factory :comment do    
    occured_at { 5.hours.ago }
    association :commentable, factory: :user
  end

end

, . ""? - , . , " " - .

+5

, . @jordanpg, , . , , , , , , :

  • user_1
  • user_2 ( ) user_1

, :

# app/models/user.rb
class User < ApplicationRecord
  has_many :stories
  has_many :comments
end

# app/models/story.rb
class Story < ApplicationRecord
  belongs_to :user
  has_many :comments, as: :commentable
end

# app/models/comment.rb
class Comment < ApplicationRecord
  belongs_to :user
  belongs_to :commentable, polymorphic: true
end

factory :

# spec/factories.rb
FactoryBot.define do

  factory :user do
    sequence(:email) {|n| "person#{n}@exmaple.com"}
    sequence(:slug) {|n| "person#{n}"}
  end

  factory :post do
    body "this is the post body"
    user
  end

  factory :comment do
    body "this is a comment on a post"
    user
    association :commentable, factory: :post
  end
end

, factory_bot , . : http://www.rubydoc.info/gems/factory_bot/file/GETTING_STARTED.md#Associations

, , :

  factory :comment_on_post, class: Comment do
    body "this is a comment on a post"
    user
    association :commentable, factory: :post
  end

  factory :comment_on_comment, class: Comment do
    body "this is a comment on a comment"
    user
    association :commentable, factory: :comment_on_post
  end
0

All Articles