Skip to content

Instantly share code, notes, and snippets.

@jkamenik
Created March 8, 2012 22:25
Show Gist options
  • Save jkamenik/2003858 to your computer and use it in GitHub Desktop.
Save jkamenik/2003858 to your computer and use it in GitHub Desktop.
Factory Girl Tests
Scenario: Has no parents
Given the following categories exist:
| name |
| Foo |
| Bar |
| Baz |
Scenario: Nested tree
Given the following categories exist:
| name | parent |
| Foo | |
| Bar | Foo |
| Baz | Bar |
# + Foo
# |+ Bar
# |- Baz
class Category < ActiveRecord::Base
acts_as_nested_set
end
FactoryGirl.define do
factory :category do
name 'Foo'
ignore do
parent nil
end
after_create do |category,attributes|
unless attributes.parent.blank?
parent = Category.find_by_name(attributes.parent)
category.move_to_child_of(parent)
end
end
end
end
requie 'factory_girl/step_definitions'
Scenario: Showing example steps
Given the following blogs exist:
| name |
| first blog |
Given a blog exists with a name of "first blog"
Given a blog exists
Given 41 blogs exist
Given 14 blogs exist with a description of "Test"
Scenario: Products
Given a product exists
# 1 product with an included file whose file_name was "small_image.png"
Given the following products exist:
| name | file name |
| No image | |
| Big image | big_image.png |
class Product < ActiveRecord::Base
mount_uploader :file, FileUploader
end
FactoryGirl.define do
factory :product do
ignore do
file_name 'small_image.png'
end
file { File.open(Rails.root.join("path/to/files",file_name)) unless file_name.blank? }
end
end
Scenario: Bad
Given a category exists with a name of "Foo"
Given a product exists with a category of "Foo"
Scenario: Good
Given the following products exist:
| name | category |
| Foo | name: Bar |
class Category < ActiveRecord::Base
end
class Product < ActiveRecord::Base
belongs_to :category
end
FactoryGirl.define do
factory :category do
name 'Foo'
end
factory :product do
association :category
name 'Bar'
end
end
Scenario: 2 users named 'John Doe', and 2 stores named "Test store"
Given a user exists
Given a store exists
Scenario: 2 users both working at the same store
Given the following users exist:
| name | store name |
| John Doe | Test store |
| Jane Doe | Test store |
Scenario: 2 stores both owned by the same person
Given the following stores exist:
| name | owner |
| MD Store | name: John Doe |
| CA Store | name: John Doe |
class User < ActiveRecord::Base
belongs_to :store
has_many :stores, :foreign_key => 'owner_id'
end
class Store < ActiveRecord::Base
belongs_to :owner, :class_name => 'User'
end
FactoryGirl.define do
factory :user do
name 'John Doe'
ignore do
store_name nil
end
store {Store.find_or_create_by_name(store_name || 'Test store')}
end
factory :store do
name 'Test store'
association :owner, :factory => :user
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment