Factory Girl Testing Setup By ThoughtBot

Factory Girl is a testing framework for Ruby On Rails written by ThoughtBot.com

This page has notes from ThoughtBot about how to do Factory Girl testing setup.
Thanks to Dan Croak, author of Factory Girl, for providing these ideas.

Related: Factory Girl Testing Speed By ThoughtBot

To create a collection of users

Suppose you have a factory like this:

  user = Factory(:user)

To create 3 users, we call the factory in a loop like this:

  users = 3.times { Factory(:user) }

To create a collection for the "many" in a has_many

Do it in FactoryGirl's after_create on the belonging object.

Suppose you have a class "User" that belongs to a "Team".

To create a team with 3 users:

  Factory.define :team_with_three_users do |team|
    team.after_create do |team_after_create|
      3.times { Factory(:user, :team => team_after_create) }

To create records that share parameters

Write a helper method.

Write a helper method. Suppose you have a User class and you want to randomly pick a team from among many teams.

  # in test/factories.rb or spec/factories.rb
  def teams
    @teams ||= 3.times { Factory(:team) }

  # Now your user factory can call the helper
  Factory.define :user |user|
    user.after_create do |user_after_create|
      user_after_create.team = teams.sample

To connect cucumber steps for dynamic factories

Parse the cucumber step then send the match as a parameter:
  Given /^typical (\w+)/ do |name|
Now we can write Gherkin features like this:
  Given a typical user.
  Given a typical team.

To do more advanced expert setup with callbacks

See this post about callbacks before and after factories:

What's Next?

blog comments powered by Disqus