From f6db21769dd39288127d61c5026b16c0d0b30512 Mon Sep 17 00:00:00 2001 From: Joe Ferris Date: Wed, 28 May 2008 21:14:57 -0400 Subject: [PATCH] Defined method_missing on Factory so that attributes can be defined by calling the attribute name as a method --- lib/factory_girl/factory.rb | 18 ++++++++++++++++++ test/factory_test.rb | 7 +++++++ 2 files changed, 25 insertions(+) diff --git a/lib/factory_girl/factory.rb b/lib/factory_girl/factory.rb index c839b68..b065d09 100644 --- a/lib/factory_girl/factory.rb +++ b/lib/factory_girl/factory.rb @@ -69,6 +69,24 @@ class Factory end end + # Calls add_attribute using the missing method name as the name of the + # attribute, so that: + # + # Factory.define :user do |f| + # f.name 'Billy Idol' + # end + # + # and: + # + # Factory.define :user do |f| + # f.add_attribute :user, 'Billy Idol' + # end + # + # are equivilent. + def method_missing (name, *args, &block) + add_attribute(name, *args, &block) + end + # Generates and returns a Hash of attributes from this factory. Attributes # can be individually overridden by passing in a Hash of attribute => value # pairs. diff --git a/test/factory_test.rb b/test/factory_test.rb index ff549ee..ea59d14 100644 --- a/test/factory_test.rb +++ b/test/factory_test.rb @@ -108,6 +108,13 @@ class FactoryTest < Test::Unit::TestCase end + should "add an attribute using the method name when passed an undefined method" do + @attr = :first_name + @value = 'Sugar' + @factory.send(@attr, @value) + assert_equal @value, @factory.attributes[@attr] + end + should "not allow attributes to be added with both a value parameter and a block" do assert_raise(ArgumentError) do @factory.add_attribute(:name, 'value') {}