Skip to content

Instantly share code, notes, and snippets.

@kf8a
Created February 24, 2015 22:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kf8a/1f57bfffad727b792860 to your computer and use it in GitHub Desktop.
Save kf8a/1f57bfffad727b792860 to your computer and use it in GitHub Desktop.

FactoryGirl has_many associations with validations

I had a user model that has_many posts, in addition the user is supposed to have at least one post. The user model contains: validates :posts, presence: true

Setting up the factory for the user model requires just a slight modification of the example code. I needed to just build the user model and attach the posts explicitly to the user in the factory.

factory :user do
    name "Joe Smith"
    
    factory :user_with_posts do 
        transient do
            post_count 5
        end
        
        after(:build) do |user, evaluator|
            user.posts = create_list(:post, evaluator.post_count, user: user)
        end
    end
end

Then I could use it in my tests with the two liner

user = FactoryGirl.build(:user_with_posts)
user.save
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment