Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

How to generate factories for Socialization in FactoryGirl

billychan edited this page · 1 revision

This page will demonstrate a simple example about how to create factories for Socialization in FactoryGirl.

Our demo app will have an Article model which belongs to user and has many comments. User can be mentioned in comments with following settings:

class User < ActiveRecord::Base
  acts_as_mentionable
end

class Comment < ActiveRecord::Base
  acts_as_mentioner
end

Our object here is to create a factory object of user who has been mentioned in several comments. Here is how:

# spec/factories.rb
FactoryGirl.define do
  factory :article do
    title "article title"
    body "article body"
    user
  end

  factory :comment do
    content: "demo comment content"
    user
    article
  end

  factory :user do
    sequence(:email) {|n| "person#{n}@example.com" }
    password "secret_password"

    # Here to define the factory for our object
    factory :user_mentioned_by_comments do
      ignore do
        comments_count 5
      end

      after(:create) do |user, evaluator|
        comments = FactoryGirl.create_list(:comment, evaluator.comments_count)
        comments.each do |comment|
          comment.mention!(user)
        end
      end

    end
  end      
end

To use the factory

user = FactoryGirl.create(:user_mentioned_by_comments)
# => Generate an user and 5 comments mentioned him
user.mentioners(Comment)
# => the 5 comments
comment = Comment.find(:last)
comment.mentionees(User)
# => Return the former created "user" object
Something went wrong with that request. Please try again.