Skip to content

Instantly share code, notes, and snippets.

@afair
Created March 19, 2014 19:01
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 afair/9648839 to your computer and use it in GitHub Desktop.
Save afair/9648839 to your computer and use it in GitHub Desktop.
Factory Girl Basics
FactoryGirl.define do
factory :user do # class:User, aliases:[:name1, :name2]
name "Ruby"
date_of_birth { 21.years.ago } # Blocked called lazily at request time
association_factory_name
association :commenter, factory: :user, attrib:"value"
factory(:admin_user) do # Inheritance
admin true
end
sequence(:name) # Auto-increment, optional initial value
sequence :email do |n| # Usage: generate :email
"person#{n}@example.com"
end
email # Generates a new value for the email attribute
alternate_email { generate(:email) } # Lazy generation
trait :admin do
is_admin true
start_at { 1.month.ago }
end
factory :week_long_published_story, traits:[:published, :week_long_publishing]
trait_name
after(:create) do |user, evaluator|
user.name.upcase! if evaluator.upcased
end
# create(:user_with_posts, posts_count: 15)
factory :user_with_posts do
ignore { post_counts 5 } # Passed attrib to ignore (and reference later)
after(:create) { build_list(:posts, post_counts }
end
after(:build || :create || stub) { block }# Callbacks
before(:build || :create || stub, &:sym_to_proc)
end
end
user = build(:user, :traitname, attrname:"value") {|u| u.setup_something } # Unsaved
user = create(:user) # Saved
user_attrs = attributes_for(:user)
users = build_list(:user, 25)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment