gabrielg-factory_girl 1.1.6

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,281 @@
1
+ class Factory
2
+
3
+ cattr_accessor :factories #:nodoc:
4
+ self.factories = {}
5
+
6
+ # An Array of strings specifying locations that should be searched for
7
+ # factory definitions. By default, factory_girl will attempt to require
8
+ # "factories," "test/factories," and "spec/factories." Only the first
9
+ # existing file will be loaded.
10
+ cattr_accessor :definition_file_paths
11
+ self.definition_file_paths = %w(factories test/factories spec/factories)
12
+
13
+ attr_reader :factory_name
14
+
15
+ # Defines a new factory that can be used by the build strategies (create and
16
+ # build) to build new objects.
17
+ #
18
+ # Arguments:
19
+ # name: (Symbol)
20
+ # A unique name used to identify this factory.
21
+ # options: (Hash)
22
+ # class: the class that will be used when generating instances for this
23
+ # factory. If not specified, the class will be guessed from the
24
+ # factory name.
25
+ #
26
+ # Yields:
27
+ # The newly created factory (Factory)
28
+ def self.define (name, options = {})
29
+ inherit_from = options.delete(:inherit)
30
+ instance = (inherit_from.nil?) ? Factory.new(name, options) : self.factories[inherit_from]
31
+ yield(instance)
32
+ self.factories[instance.factory_name] = instance
33
+ end
34
+
35
+ def build_class #:nodoc:
36
+ @build_class ||= class_for(@options[:class] || factory_name)
37
+ end
38
+
39
+ def initialize (name, options = {}) #:nodoc:
40
+ options.assert_valid_keys(:class)
41
+ @factory_name = factory_name_for(name)
42
+ @options = options
43
+ @attributes = []
44
+ @static_attributes = {}
45
+ @lazy_attribute_blocks = {}
46
+ @lazy_attribute_names = []
47
+ @callbacks = {}
48
+ end
49
+
50
+ # Adds an attribute that should be assigned on generated instances for this
51
+ # factory.
52
+ #
53
+ # This method should be called with either a value or block, but not both. If
54
+ # called with a block, the attribute will be generated "lazily," whenever an
55
+ # instance is generated. Lazy attribute blocks will not be called if that
56
+ # attribute is overriden for a specific instance.
57
+ #
58
+ # When defining lazy attributes, an instance of Factory::AttributeProxy will
59
+ # be yielded, allowing associations to be built using the correct build
60
+ # strategy.
61
+ #
62
+ # Arguments:
63
+ # name: (Symbol)
64
+ # The name of this attribute. This will be assigned using :"#{name}=" for
65
+ # generated instances.
66
+ # value: (Object)
67
+ # If no block is given, this value will be used for this attribute.
68
+ def add_attribute (name, value = nil, &block)
69
+ attribute = Attribute.new(name, value, block)
70
+
71
+ if attribute_defined?(attribute.name)
72
+ raise AttributeDefinitionError, "Attribute already defined: #{name}"
73
+ end
74
+
75
+ @attributes << attribute
76
+ end
77
+
78
+ # Calls add_attribute using the missing method name as the name of the
79
+ # attribute, so that:
80
+ #
81
+ # Factory.define :user do |f|
82
+ # f.name 'Billy Idol'
83
+ # end
84
+ #
85
+ # and:
86
+ #
87
+ # Factory.define :user do |f|
88
+ # f.add_attribute :name, 'Billy Idol'
89
+ # end
90
+ #
91
+ # are equivilent.
92
+ def method_missing (name, *args, &block)
93
+ add_attribute(name, *args, &block)
94
+ end
95
+
96
+ # Adds an attribute that builds an association. The associated instance will
97
+ # be built using the same build strategy as the parent instance.
98
+ #
99
+ # Example:
100
+ # Factory.define :user do |f|
101
+ # f.name 'Joey'
102
+ # end
103
+ #
104
+ # Factory.define :post do |f|
105
+ # f.association :author, :factory => :user
106
+ # end
107
+ #
108
+ # Arguments:
109
+ # name: (Symbol)
110
+ # The name of this attribute.
111
+ # options: (Hash)
112
+ # factory: (Symbol)
113
+ # The name of the factory to use when building the associated instance.
114
+ # If no name is given, the name of the attribute is assumed to be the
115
+ # name of the factory. For example, a "user" association will by
116
+ # default use the "user" factory.
117
+ def association (name, options = {})
118
+ name = name.to_sym
119
+ options = options.symbolize_keys
120
+ association_factory = (options[:count] ? (options[:factory] || name.to_s.singularize) : (options[:factory] || name)).to_sym
121
+
122
+ add_attribute(name) { |a| a.association(association_factory, {}, {:count => options[:count]}) }
123
+ end
124
+
125
+ def attributes_for (attrs = {}) #:nodoc:
126
+ build_attributes_hash(attrs, :attributes_for)
127
+ end
128
+
129
+ def build (attrs = {}) #:nodoc:
130
+ build_instance(attrs, :build)
131
+ end
132
+
133
+ def create (attrs = {}) #:nodoc:
134
+ instance = build_instance(attrs, :create)
135
+ instance.save!
136
+ @callbacks[:after_create].call(instance) unless @callbacks[:after_create].nil?
137
+ instance
138
+ end
139
+
140
+ # Allows a block to be evaluated after the factory object has been built, but before
141
+ # it is saved to the database. The block is passed the instance so you can do stuff
142
+ # to it. For example, maybe you want to stub a method whose result normally relies on
143
+ # complex computation on attributes and associations:
144
+ #
145
+ # Factory.define :a_boy_that_never_goes_out, :class => Boy do |f|
146
+ # f.name 'Morrisey'
147
+ # f.after_build do |b|
148
+ # b.stubs(:goes_out).returns(false)
149
+ # end
150
+ # end
151
+ def after_build(&block)
152
+ @callbacks[:after_build] = block
153
+ end
154
+
155
+ # Allows a block to be evaluated after the factory object has been saved to the
156
+ # database. The block is passed the instance so you can do stuff to it. For example
157
+ # maybe you want to stub a method whose result normally relies on complex computation
158
+ # on attributes and associations:
159
+ #
160
+ # Factory.define :a_boy_that_never_goes_out, :class => Boy do |f|
161
+ # f.name 'Morrisey'
162
+ # f.after_create do |b|
163
+ # b.stubs(:goes_out).returns(false)
164
+ # end
165
+ # end
166
+ def after_create(&block)
167
+ @callbacks[:after_create] = block
168
+ end
169
+
170
+ class << self
171
+
172
+ # Generates and returns a Hash of attributes from this factory. Attributes
173
+ # can be individually overridden by passing in a Hash of attribute => value
174
+ # pairs.
175
+ #
176
+ # Arguments:
177
+ # attrs: (Hash)
178
+ # Attributes to overwrite for this set.
179
+ #
180
+ # Returns:
181
+ # A set of attributes that can be used to build an instance of the class
182
+ # this factory generates. (Hash)
183
+ def attributes_for (name, attrs = {})
184
+ factory_by_name(name).attributes_for(attrs)
185
+ end
186
+
187
+ # Generates and returns an instance from this factory. Attributes can be
188
+ # individually overridden by passing in a Hash of attribute => value pairs.
189
+ #
190
+ # Arguments:
191
+ # attrs: (Hash)
192
+ # See attributes_for
193
+ #
194
+ # Returns:
195
+ # An instance of the class this factory generates, with generated
196
+ # attributes assigned.
197
+ def build (name, attrs = {})
198
+ factory_by_name(name).build(attrs)
199
+ end
200
+
201
+ # Generates, saves, and returns an instance from this factory. Attributes can
202
+ # be individually overridden by passing in a Hash of attribute => value
203
+ # pairs.
204
+ #
205
+ # If the instance is not valid, an ActiveRecord::Invalid exception will be
206
+ # raised.
207
+ #
208
+ # Arguments:
209
+ # attrs: (Hash)
210
+ # See attributes_for
211
+ #
212
+ # Returns:
213
+ # A saved instance of the class this factory generates, with generated
214
+ # attributes assigned.
215
+ def create (name, attrs = {})
216
+ factory_by_name(name).create(attrs)
217
+ end
218
+
219
+ def find_definitions #:nodoc:
220
+ definition_file_paths.each do |path|
221
+ begin
222
+ require(path)
223
+ break
224
+ rescue LoadError
225
+ end
226
+ end
227
+ end
228
+
229
+ private
230
+
231
+ def factory_by_name (name)
232
+ factories[name.to_sym] or raise ArgumentError.new("No such factory: #{name.to_s}")
233
+ end
234
+
235
+ end
236
+
237
+ private
238
+
239
+ def build_attributes_hash (values, strategy)
240
+ values = values.symbolize_keys
241
+ passed_keys = values.keys.collect {|key| Factory.aliases_for(key) }.flatten
242
+ @attributes.each do |attribute|
243
+ unless passed_keys.include?(attribute.name)
244
+ proxy = AttributeProxy.new(self, attribute.name, strategy, values)
245
+ values[attribute.name] = attribute.value(proxy)
246
+ end
247
+ end
248
+ values
249
+ end
250
+
251
+ def build_instance (override, strategy)
252
+ instance = build_class.new
253
+ attrs = build_attributes_hash(override, strategy)
254
+ attrs.each do |attr, value|
255
+ instance.send(:"#{attr}=", value)
256
+ end
257
+ @callbacks[:after_build].call(instance) unless @callbacks[:after_build].nil?
258
+ instance
259
+ end
260
+
261
+ def class_for (class_or_to_s)
262
+ if class_or_to_s.respond_to?(:to_sym)
263
+ class_or_to_s.to_s.classify.constantize
264
+ else
265
+ class_or_to_s
266
+ end
267
+ end
268
+
269
+ def factory_name_for (class_or_to_s)
270
+ if class_or_to_s.respond_to?(:to_sym)
271
+ class_or_to_s.to_sym
272
+ else
273
+ class_or_to_s.to_s.underscore.to_sym
274
+ end
275
+ end
276
+
277
+ def attribute_defined? (name)
278
+ !@attributes.detect {|attr| attr.name == name }.nil?
279
+ end
280
+
281
+ end
@@ -0,0 +1,56 @@
1
+ class Factory
2
+
3
+ class Sequence
4
+
5
+ def initialize (&proc) #:nodoc:
6
+ @proc = proc
7
+ @value = 0
8
+ end
9
+
10
+ # Returns the next value for this sequence
11
+ def next
12
+ @value += 1
13
+ @proc.call(@value)
14
+ end
15
+
16
+ end
17
+
18
+ cattr_accessor :sequences #:nodoc:
19
+ self.sequences = {}
20
+
21
+ # Defines a new sequence that can be used to generate unique values in a specific format.
22
+ #
23
+ # Arguments:
24
+ # name: (Symbol)
25
+ # A unique name for this sequence. This name will be referenced when
26
+ # calling next to generate new values from this sequence.
27
+ # block: (Proc)
28
+ # The code to generate each value in the sequence. This block will be
29
+ # called with a unique number each time a value in the sequence is to be
30
+ # generated. The block should return the generated value for the
31
+ # sequence.
32
+ #
33
+ # Example:
34
+ #
35
+ # Factory.sequence(:email) {|n| "somebody_#{n}@example.com" }
36
+ def self.sequence (name, &block)
37
+ self.sequences[name] = Sequence.new(&block)
38
+ end
39
+
40
+ # Generates and returns the next value in a sequence.
41
+ #
42
+ # Arguments:
43
+ # name: (Symbol)
44
+ # The name of the sequence that a value should be generated for.
45
+ #
46
+ # Returns:
47
+ # The next value in the sequence. (Object)
48
+ def self.next (sequence)
49
+ unless self.sequences.key?(sequence)
50
+ raise "No such sequence: #{sequence}"
51
+ end
52
+
53
+ self.sequences[sequence].next
54
+ end
55
+
56
+ end
@@ -0,0 +1,16 @@
1
+ require 'active_support'
2
+ require 'factory_girl/factory'
3
+ require 'factory_girl/attribute_proxy'
4
+ require 'factory_girl/attribute'
5
+ require 'factory_girl/sequence'
6
+ require 'factory_girl/aliases'
7
+
8
+ # Shortcut for Factory.create.
9
+ #
10
+ # Example:
11
+ # Factory(:user, :name => 'Joe')
12
+ def Factory (name, attrs = {})
13
+ Factory.create(name, attrs)
14
+ end
15
+
16
+ Factory.find_definitions
@@ -0,0 +1,29 @@
1
+ require(File.join(File.dirname(__FILE__), 'test_helper'))
2
+
3
+ class AliasesTest < Test::Unit::TestCase
4
+
5
+ should "include an attribute as an alias for itself by default" do
6
+ assert Factory.aliases_for(:test).include?(:test)
7
+ end
8
+
9
+ should "include the root of a foreign key as an alias by default" do
10
+ assert Factory.aliases_for(:test_id).include?(:test)
11
+ end
12
+
13
+ should "include an attribute's foreign key as an alias by default" do
14
+ assert Factory.aliases_for(:test).include?(:test_id)
15
+ end
16
+
17
+ context "after adding an alias" do
18
+
19
+ setup do
20
+ Factory.alias(/(.*)_suffix/, '\1')
21
+ end
22
+
23
+ should "return the alias in the aliases list" do
24
+ assert Factory.aliases_for(:test_suffix).include?(:test)
25
+ end
26
+
27
+ end
28
+
29
+ end
@@ -0,0 +1,101 @@
1
+ require(File.join(File.dirname(__FILE__), 'test_helper'))
2
+
3
+ class AttributeProxyTest < Test::Unit::TestCase
4
+
5
+ context "an association proxy" do
6
+
7
+ setup do
8
+ @factory = mock('factory')
9
+ @attr = :user
10
+ @attrs = { :first_name => 'John' }
11
+ @strategy = :create
12
+ @proxy = Factory::AttributeProxy.new(@factory, @attr, @strategy, @attrs)
13
+ end
14
+
15
+ should "have a factory" do
16
+ assert_equal @factory, @proxy.factory
17
+ end
18
+
19
+ should "have an attribute name" do
20
+ assert_equal @attr, @proxy.attribute_name
21
+ end
22
+
23
+ should "have a build strategy" do
24
+ assert_equal @strategy, @proxy.strategy
25
+ end
26
+
27
+ should "have attributes" do
28
+ assert_equal @attrs, @proxy.current_values
29
+ end
30
+
31
+ context "building an association" do
32
+
33
+ setup do
34
+ @association = mock('built-user')
35
+ @name = :user
36
+ @attribs = { :first_name => 'Billy' }
37
+
38
+ Factory.stubs(@strategy).returns(@association)
39
+ end
40
+
41
+ should "delegate to the appropriate method on Factory" do
42
+ Factory.expects(@strategy).with(@name, @attribs).returns(@association)
43
+ @proxy.association(@name, @attribs)
44
+ end
45
+
46
+ should "return the built association" do
47
+ assert_equal @association, @proxy.association(@name)
48
+ end
49
+
50
+ end
51
+
52
+ context "building an association using the attributes_for strategy" do
53
+
54
+ setup do
55
+ @strategy = :attributes_for
56
+ @proxy = Factory::AttributeProxy.new(@factory, @attr, @strategy, @attrs)
57
+ end
58
+
59
+ should "not build the association" do
60
+ Factory.expects(@strategy).never
61
+ @proxy.association(:user)
62
+ end
63
+
64
+ should "return nil for the association" do
65
+ Factory.stubs(@strategy).returns(:user)
66
+ assert_nil @proxy.association(:user)
67
+ end
68
+
69
+ end
70
+
71
+ context "fetching the value of an attribute" do
72
+
73
+ setup do
74
+ @attr = :first_name
75
+ end
76
+
77
+ should "return the correct value" do
78
+ assert_equal @attrs[@attr], @proxy.value_for(@attr)
79
+ end
80
+
81
+ should "call value_for for undefined methods" do
82
+ assert_equal @attrs[@attr], @proxy.send(@attr)
83
+ end
84
+
85
+ end
86
+
87
+ context "fetching the value of an undefined attribute" do
88
+
89
+ setup do
90
+ @attr = :beachball
91
+ end
92
+
93
+ should "raise an ArgumentError" do
94
+ assert_raise(ArgumentError) { @proxy.value_for(@attr) }
95
+ end
96
+
97
+ end
98
+
99
+ end
100
+
101
+ end
@@ -0,0 +1,70 @@
1
+ require(File.join(File.dirname(__FILE__), 'test_helper'))
2
+
3
+ class AttributeTest < Test::Unit::TestCase
4
+
5
+ def setup
6
+ @proxy = mock('attribute-proxy')
7
+ end
8
+
9
+ context "an attribute" do
10
+
11
+ setup do
12
+ @name = :user
13
+ @attr = Factory::Attribute.new(@name, 'test', nil)
14
+ end
15
+
16
+ should "have a name" do
17
+ assert_equal @name, @attr.name
18
+ end
19
+
20
+ end
21
+
22
+ context "an attribute with a static value" do
23
+
24
+ setup do
25
+ @value = 'test'
26
+ @attr = Factory::Attribute.new(:user, @value, nil)
27
+ end
28
+
29
+ should "return the value" do
30
+ assert_equal @value, @attr.value(@proxy)
31
+ end
32
+
33
+ end
34
+
35
+ context "an attribute with a lazy value" do
36
+
37
+ setup do
38
+ @block = lambda { 'value' }
39
+ @attr = Factory::Attribute.new(:user, nil, @block)
40
+ end
41
+
42
+ should "call the block to return a value" do
43
+ assert_equal 'value', @attr.value(@proxy)
44
+ end
45
+
46
+ should "yield the attribute proxy to the block" do
47
+ @block = lambda {|a| a }
48
+ @attr = Factory::Attribute.new(:user, nil, @block)
49
+ assert_equal @proxy, @attr.value(@proxy)
50
+ end
51
+
52
+ end
53
+
54
+ should "raise an error when defining an attribute writer" do
55
+ assert_raise Factory::AttributeDefinitionError do
56
+ Factory::Attribute.new('test=', nil, nil)
57
+ end
58
+ end
59
+
60
+ should "not allow attributes to be added with both a value parameter and a block" do
61
+ assert_raise(Factory::AttributeDefinitionError) do
62
+ Factory::Attribute.new(:name, 'value', lambda {})
63
+ end
64
+ end
65
+
66
+ should "convert names to symbols" do
67
+ assert_equal :name, Factory::Attribute.new('name', nil, nil).name
68
+ end
69
+
70
+ end