Created
March 19, 2014 19:01
-
-
Save afair/9648839 to your computer and use it in GitHub Desktop.
Factory Girl Basics
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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