Skip to content

Instantly share code, notes, and snippets.

@vladvinnikov
Created January 11, 2012 05:33
Show Gist options
  • Save vladvinnikov/1593219 to your computer and use it in GitHub Desktop.
Save vladvinnikov/1593219 to your computer and use it in GitHub Desktop.
Factory example

Here's a sample test/factories.rb:

# Factories
Factory.define :article do |t|
	t.association :section # An article belongs to a section
	t.title {|x| "#{x.section.name}Article#{Factory.next(:count)}" }  # Use brackets when you're calling a sequence
	t.author "Author Bob"
    # Assuming you have put "require 'forgery' " in the correct place.  It could just be in your seeds.rb file.
	t.body Forgery::LoremIpsum.paragraphs(5)
	t.status "status here"
	t.comments_allowed false
	t.notes "notes here"
	t.teaser "I am a teaser."
	t.styles "styles here"
end

Factory.define :comment do |t|
	t.association :article # A comment belongs to an article
	t.body Forgery::LoremIpsum.sentence
	t.full_name "Commenter Bob"
	t.email { Factory.next(:email) }
end

Factory.define :page do |t|
	t.title { "Page#{Factory.next(:count)}" } # Again, remember to have the brackets here when you're calling a sequence.
	t.styles "styles here"
	t.body Forgery::LoremIpsum.paragraphs(5)
end

# Sequences - it's okay to call them in different factories.
Factory.sequence :count do |n|
	n
end

Factory.sequence :email do |n|
   names = %w[ Joe Bob Sue ]
   # randomly select a name from the names array for the email, so you might get "[email protected]"
   "#{names[rand 3]}#{n}@somewhere.com"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment