Allow recursive associations from cucumber table arguments

This commit is contained in:
Fernando Ultremare 2010-10-28 14:20:24 -02:00 committed by Joe Ferris
parent 36c17ad8c8
commit 1b28476713
4 changed files with 52 additions and 2 deletions

View File

@ -123,3 +123,29 @@ Feature: Use step definitions generated by factories
And 2 categories exist
And 2 categories exist with a name of "Future"
Then there should be 6 categories
Scenario: create a post with an existing category group
Given the following category exists:
| ID | name | category group |
| 123 | fiction | Name: books |
And the following post exists:
| Title | Author | Category |
| a title | Name: Joe | Category Group: Name: books |
Then I should find the following for the last post:
| title | category_id |
| a title | 123 |
Scenario: create a post with an existing category group and a new category
Given the following category group exists:
| ID | name |
| 456 | books |
And the following post exists:
| Title | Author | Category |
| a title | Name: Joe | Category Group: Name: books |
Then I should find the following for the last post:
| title |
| a title |
And I should find the following for the last category:
| category_group_id |
| 456 |

View File

@ -15,4 +15,6 @@ Before do
Post.delete_all
User.delete_all
Category.delete_all
CategoryGroup.delete_all
end

View File

@ -12,7 +12,12 @@ class CreateSchema < ActiveRecord::Migration
t.string :body
end
create_table :category_groups, :force => true do |t|
t.string :name
end
create_table :categories, :force => true do |t|
t.integer :category_group_id
t.string :name
end
@ -28,7 +33,11 @@ CreateSchema.suppress_messages { CreateSchema.migrate(:up) }
class User < ActiveRecord::Base
end
class CategoryGroup < ActiveRecord::Base
end
class Category < ActiveRecord::Base
belongs_to :category_group
end
class Post < ActiveRecord::Base
@ -48,6 +57,11 @@ end
Factory.define :category do |f|
f.name "programming"
f.association :category_group
end
Factory.define :category_group do |f|
f.name "tecnhology"
end
Factory.define :post do |f|
@ -60,3 +74,4 @@ Factory.define :non_active_record do |f|
end
require 'factory_girl/step_definitions'

View File

@ -1,11 +1,17 @@
module FactoryGirlStepHelpers
def convert_association_string_to_instance(factory_name, assignment)
attribute, value = assignment.split(':', 2)
return if value.blank?
attributes = convert_human_hash_to_attribute_hash(attribute => value.strip)
factory = FactoryGirl.factory_by_name(factory_name)
attributes = convert_human_hash_to_attribute_hash({attribute => value.strip}, factory.associations)
attributes_find = {}
attributes.each do |k, v|
k = "#{k}_id" if v.is_a? ActiveRecord::Base
attributes_find[k] = v
end
model_class = factory.build_class
model_class.find(:first, :conditions => attributes) or
model_class.find(:first, :conditions => attributes_find) or
Factory(factory_name, attributes)
end
@ -51,3 +57,4 @@ FactoryGirl.factories.values.each do |factory|
end
end
end