masa-iwasaki-factory_girl 1.2.1.1

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,395 @@
1
+ class Factory
2
+
3
+ # Raised when a factory is defined that attempts to instantiate itself.
4
+ class AssociationDefinitionError < RuntimeError
5
+ end
6
+
7
+ class << self
8
+ attr_accessor :factories #:nodoc:
9
+
10
+ # An array of used in find_or_create to keep AR instances created
11
+ # by Proxy::Create
12
+ attr_accessor :instances
13
+
14
+ # An Array of strings specifying locations that should be searched for
15
+ # factory definitions. By default, factory_girl will attempt to require
16
+ # "factories," "test/factories," and "spec/factories." Only the first
17
+ # existing file will be loaded.
18
+ attr_accessor :definition_file_paths
19
+ end
20
+
21
+ self.factories = {}
22
+ self.instances = {}
23
+ self.definition_file_paths = %w(factories test/factories spec/factories)
24
+
25
+ attr_reader :factory_name #:nodoc:
26
+ attr_reader :attributes #:nodoc:
27
+
28
+ # Defines a new factory that can be used by the build strategies (create and
29
+ # build) to build new objects.
30
+ #
31
+ # Arguments:
32
+ # * name: +Symbol+ or +String+
33
+ # A unique name used to identify this factory.
34
+ # * options: +Hash+
35
+ #
36
+ # Options:
37
+ # * class: +Symbol+, +Class+, or +String+
38
+ # The class that will be used when generating instances for this factory. If not specified, the class will be guessed from the factory name.
39
+ # * parent: +Symbol+
40
+ # The parent factory. If specified, the attributes from the parent
41
+ # factory will be copied to the current one with an ability to override
42
+ # them.
43
+ # * default_strategy: +Symbol+
44
+ # The strategy that will be used by the Factory shortcut method.
45
+ # Defaults to :create.
46
+ #
47
+ # Yields: +Factory+
48
+ # The newly created factory.
49
+ def self.define (name, options = {})
50
+ instance = Factory.new(name, options)
51
+ yield(instance)
52
+ if parent = options.delete(:parent)
53
+ instance.inherit_from(Factory.factory_by_name(parent))
54
+ end
55
+ self.factories[instance.factory_name] = instance
56
+ end
57
+
58
+ def class_name #:nodoc:
59
+ @options[:class] || factory_name
60
+ end
61
+
62
+ def build_class #:nodoc:
63
+ @build_class ||= class_for(class_name)
64
+ end
65
+
66
+ def default_strategy #:nodoc:
67
+ @options[:default_strategy] || :find_or_create
68
+ end
69
+
70
+ def initialize (name, options = {}) #:nodoc:
71
+ assert_valid_options(options)
72
+ @factory_name = factory_name_for(name)
73
+ @options = options
74
+ @attributes = []
75
+ end
76
+
77
+ def inherit_from(parent) #:nodoc:
78
+ @options[:class] ||= parent.class_name
79
+ parent.attributes.each do |attribute|
80
+ unless attribute_defined?(attribute.name)
81
+ @attributes << attribute.clone
82
+ end
83
+ end
84
+ end
85
+
86
+ # Adds an attribute that should be assigned on generated instances for this
87
+ # factory.
88
+ #
89
+ # This method should be called with either a value or block, but not both. If
90
+ # called with a block, the attribute will be generated "lazily," whenever an
91
+ # instance is generated. Lazy attribute blocks will not be called if that
92
+ # attribute is overriden for a specific instance.
93
+ #
94
+ # When defining lazy attributes, an instance of Factory::Proxy will
95
+ # be yielded, allowing associations to be built using the correct build
96
+ # strategy.
97
+ #
98
+ # Arguments:
99
+ # * name: +Symbol+ or +String+
100
+ # The name of this attribute. This will be assigned using :"#{name}=" for
101
+ # generated instances.
102
+ # * value: +Object+
103
+ # If no block is given, this value will be used for this attribute.
104
+ def add_attribute (name, value = nil, &block)
105
+ if block_given?
106
+ if value
107
+ raise AttributeDefinitionError, "Both value and block given"
108
+ else
109
+ attribute = Attribute::Dynamic.new(name, block)
110
+ end
111
+ else
112
+ attribute = Attribute::Static.new(name, value)
113
+ end
114
+
115
+ if attribute_defined?(attribute.name)
116
+ raise AttributeDefinitionError, "Attribute already defined: #{name}"
117
+ end
118
+
119
+ @attributes << attribute
120
+ end
121
+
122
+ # Calls add_attribute using the missing method name as the name of the
123
+ # attribute, so that:
124
+ #
125
+ # Factory.define :user do |f|
126
+ # f.name 'Billy Idol'
127
+ # end
128
+ #
129
+ # and:
130
+ #
131
+ # Factory.define :user do |f|
132
+ # f.add_attribute :name, 'Billy Idol'
133
+ # end
134
+ #
135
+ # are equivilent.
136
+ def method_missing (name, *args, &block)
137
+ add_attribute(name, *args, &block)
138
+ end
139
+
140
+ # Adds an attribute that builds an association. The associated instance will
141
+ # be built using the same build strategy as the parent instance.
142
+ #
143
+ # Example:
144
+ # Factory.define :user do |f|
145
+ # f.name 'Joey'
146
+ # end
147
+ #
148
+ # Factory.define :post do |f|
149
+ # f.association :author, :factory => :user
150
+ # end
151
+ #
152
+ # Arguments:
153
+ # * name: +Symbol+
154
+ # The name of this attribute.
155
+ # * options: +Hash+
156
+ #
157
+ # Options:
158
+ # * factory: +Symbol+ or +String+
159
+ # The name of the factory to use when building the associated instance.
160
+ # If no name is given, the name of the attribute is assumed to be the
161
+ # name of the factory. For example, a "user" association will by
162
+ # default use the "user" factory.
163
+ def association (name, options = {})
164
+ factory_name = options.delete(:factory) || name
165
+ if factory_name_for(factory_name) == self.factory_name
166
+ raise AssociationDefinitionError, "Self-referencing association '#{name}' in factory '#{self.factory_name}'"
167
+ end
168
+ @attributes << Attribute::Association.new(name, factory_name, options)
169
+ end
170
+
171
+ # Adds an attribute that will have unique values generated by a sequence with
172
+ # a specified format.
173
+ #
174
+ # The result of:
175
+ # Factory.define :user do |f|
176
+ # f.sequence(:email) { |n| "person#{n}@example.com" }
177
+ # end
178
+ #
179
+ # Is equal to:
180
+ # Factory.sequence(:email) { |n| "person#{n}@example.com" }
181
+ #
182
+ # Factory.define :user do |f|
183
+ # f.email { Factory.next(:email) }
184
+ # end
185
+ #
186
+ # Except that no globally available sequence will be defined.
187
+ def sequence (name, &block)
188
+ s = Sequence.new(&block)
189
+ add_attribute(name) { s.next }
190
+ end
191
+
192
+ # Generates and returns a Hash of attributes from this factory. Attributes
193
+ # can be individually overridden by passing in a Hash of attribute => value
194
+ # pairs.
195
+ #
196
+ # Arguments:
197
+ # * name: +Symbol+ or +String+
198
+ # The name of the factory that should be used.
199
+ # * overrides: +Hash+
200
+ # Attributes to overwrite for this set.
201
+ #
202
+ # Returns: +Hash+
203
+ # A set of attributes that can be used to build an instance of the class
204
+ # this factory generates.
205
+ def self.attributes_for (name, overrides = {})
206
+ factory_by_name(name).run(Proxy::AttributesFor, overrides)
207
+ end
208
+
209
+ # Generates and returns an instance from this factory. Attributes can be
210
+ # individually overridden by passing in a Hash of attribute => value pairs.
211
+ #
212
+ # Arguments:
213
+ # * name: +Symbol+ or +String+
214
+ # The name of the factory that should be used.
215
+ # * overrides: +Hash+
216
+ # Attributes to overwrite for this instance.
217
+ #
218
+ # Returns: +Object+
219
+ # An instance of the class this factory generates, with generated attributes
220
+ # assigned.
221
+ def self.build (name, overrides = {})
222
+ factory_by_name(name).run(Proxy::Build, overrides)
223
+ end
224
+
225
+ # Generates, saves, and returns an instance from this factory. Attributes can
226
+ # be individually overridden by passing in a Hash of attribute => value
227
+ # pairs.
228
+ #
229
+ # Instances are saved using the +save!+ method, so ActiveRecord models will
230
+ # raise ActiveRecord::RecordInvalid exceptions for invalid attribute sets.
231
+ #
232
+ # Arguments:
233
+ # * name: +Symbol+ or +String+
234
+ # The name of the factory that should be used.
235
+ # * overrides: +Hash+
236
+ # Attributes to overwrite for this instance.
237
+ #
238
+ # Returns: +Object+
239
+ # A saved instance of the class this factory generates, with generated
240
+ # attributes assigned.
241
+ def self.create (name, overrides = {})
242
+ factory_by_name(name).run(Proxy::Create, overrides)
243
+ end
244
+
245
+ # Returns an object if an instance from this factory was already created.
246
+ # Or call self.create and register an instance to the list of instances.
247
+ #
248
+ # Arguments:
249
+ # * name: +Symbol+ or +String+
250
+ # The name of the factory that should be used.
251
+ # * overrides: +Hash+
252
+ # Attributes to overwrite for this instance.
253
+ #
254
+ # Returns: +Object+
255
+ # A saved instance of the class this factory generates, with generated
256
+ # attributes assigned.
257
+ def self.find_or_create(name, overrides = {})
258
+ if self.instances[name].nil?
259
+ self.instances[name] = self.create(name, overrides)
260
+ else
261
+ # Need reloading in terms of tearing down of fixtures on each test
262
+ begin
263
+ self.instances[name].reload
264
+ rescue ActiveRecord::RecordNotFound
265
+ self.instances[name] = self.create(name, overrides)
266
+ rescue
267
+ # TODO: Better handling for other exceptions if it is needed
268
+ self.instances[name] = self.create(name, overrides)
269
+ end
270
+ end
271
+
272
+ self.instances[name]
273
+ end
274
+
275
+ # Generates and returns an object with all attributes from this factory
276
+ # stubbed out. Attributes can be individually overridden by passing in a Hash
277
+ # of attribute => value pairs.
278
+ #
279
+ # Arguments:
280
+ # * name: +Symbol+ or +String+
281
+ # The name of the factory that should be used.
282
+ # * overrides: +Hash+
283
+ # Attributes to overwrite for this instance.
284
+ #
285
+ # Returns: +Object+
286
+ # An object with generated attributes stubbed out.
287
+ def self.stub (name, overrides = {})
288
+ factory_by_name(name).run(Proxy::Stub, overrides)
289
+ end
290
+
291
+ # Executes the default strategy for the given factory. This is usually create,
292
+ # but it can be overridden for each factory.
293
+ #
294
+ # Arguments:
295
+ # * name: +Symbol+ or +String+
296
+ # The name of the factory that should be used.
297
+ # * overrides: +Hash+
298
+ # Attributes to overwrite for this instance.
299
+ #
300
+ # Returns: +Object+
301
+ # The result of the default strategy.
302
+ def self.default_strategy (name, overrides = {})
303
+ self.send(factory_by_name(name).default_strategy, name, overrides)
304
+ end
305
+
306
+ def self.find_definitions #:nodoc:
307
+ definition_file_paths.each do |path|
308
+ require("#{path}.rb") if File.exists?("#{path}.rb")
309
+
310
+ if File.directory? path
311
+ Dir[File.join(path, '*.rb')].each do |file|
312
+ require file
313
+ end
314
+ end
315
+ end
316
+ end
317
+
318
+ def run (proxy_class, overrides) #:nodoc:
319
+ proxy = proxy_class.new(build_class)
320
+ overrides = symbolize_keys(overrides)
321
+ overrides.each {|attr, val| proxy.set(attr, val) }
322
+ passed_keys = overrides.keys.collect {|k| Factory.aliases_for(k) }.flatten
323
+ @attributes.each do |attribute|
324
+ unless passed_keys.include?(attribute.name)
325
+ attribute.add_to(proxy)
326
+ end
327
+ end
328
+ proxy.result
329
+ end
330
+
331
+ private
332
+
333
+ def self.factory_by_name (name)
334
+ factories[name.to_sym] or raise ArgumentError.new("No such factory: #{name.to_s}")
335
+ end
336
+
337
+ def class_for (class_or_to_s)
338
+ if class_or_to_s.respond_to?(:to_sym)
339
+ Object.const_get(variable_name_to_class_name(class_or_to_s))
340
+ else
341
+ class_or_to_s
342
+ end
343
+ end
344
+
345
+ def factory_name_for (class_or_to_s)
346
+ if class_or_to_s.respond_to?(:to_sym)
347
+ class_or_to_s.to_sym
348
+ else
349
+ class_name_to_variable_name(class_or_to_s).to_sym
350
+ end
351
+ end
352
+
353
+ def attribute_defined? (name)
354
+ !@attributes.detect {|attr| attr.name == name }.nil?
355
+ end
356
+
357
+ def assert_valid_options(options)
358
+ invalid_keys = options.keys - [:class, :parent, :default_strategy]
359
+ unless invalid_keys == []
360
+ raise ArgumentError, "Unknown arguments: #{invalid_keys.inspect}"
361
+ end
362
+ assert_valid_strategy(options[:default_strategy]) if options[:default_strategy]
363
+ end
364
+
365
+ def assert_valid_strategy(strategy)
366
+ unless Factory::Proxy.const_defined? variable_name_to_class_name(strategy)
367
+ raise ArgumentError, "Unknown strategy: #{strategy}"
368
+ end
369
+ end
370
+
371
+ # Based on ActiveSupport's underscore inflector
372
+ def class_name_to_variable_name(name)
373
+ name.to_s.gsub(/::/, '/').
374
+ gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
375
+ gsub(/([a-z\d])([A-Z])/,'\1_\2').
376
+ tr("-", "_").
377
+ downcase
378
+ end
379
+
380
+ # Based on ActiveSupport's camelize inflector
381
+ def variable_name_to_class_name(name)
382
+ name.to_s.
383
+ gsub(/\/(.?)/) { "::#{$1.upcase}" }.
384
+ gsub(/(?:^|_)(.)/) { $1.upcase }
385
+ end
386
+
387
+ # From ActiveSupport
388
+ def symbolize_keys(hash)
389
+ hash.inject({}) do |options, (key, value)|
390
+ options[(key.to_sym rescue key) || key] = value
391
+ options
392
+ end
393
+ end
394
+
395
+ end
@@ -0,0 +1,21 @@
1
+ class Factory
2
+ class Proxy #:nodoc:
3
+ class AttributesFor < Proxy #:nodoc:
4
+ def initialize(klass)
5
+ @hash = {}
6
+ end
7
+
8
+ def get(attribute)
9
+ @hash[attribute]
10
+ end
11
+
12
+ def set(attribute, value)
13
+ @hash[attribute] = value
14
+ end
15
+
16
+ def result
17
+ @hash
18
+ end
19
+ end
20
+ end
21
+ end
@@ -0,0 +1,29 @@
1
+ class Factory
2
+ class Proxy #:nodoc:
3
+ class Build < Proxy #:nodoc:
4
+ def initialize(klass)
5
+ @instance = klass.new
6
+ end
7
+
8
+ def get(attribute)
9
+ @instance.send(attribute)
10
+ end
11
+
12
+ def set(attribute, value)
13
+ @instance.send(:"#{attribute}=", value)
14
+ end
15
+
16
+ def associate(name, factory, attributes)
17
+ set(name, Factory.default_strategy(factory, attributes))
18
+ end
19
+
20
+ def association(factory, overrides = {})
21
+ Factory.default_strategy(factory, overrides)
22
+ end
23
+
24
+ def result
25
+ @instance
26
+ end
27
+ end
28
+ end
29
+ end
@@ -0,0 +1,10 @@
1
+ class Factory
2
+ class Proxy #:nodoc:
3
+ class Create < Build #:nodoc:
4
+ def result
5
+ @instance.save!
6
+ @instance
7
+ end
8
+ end
9
+ end
10
+ end
@@ -0,0 +1,49 @@
1
+ class Factory
2
+ class Proxy
3
+ class Stub < Proxy #:nodoc:
4
+ @@next_id = 1000
5
+
6
+ def initialize(klass)
7
+ @stub = klass.new
8
+ @stub.id = next_id
9
+ @stub.instance_eval do
10
+ def new_record?
11
+ id.nil?
12
+ end
13
+
14
+ def connection
15
+ raise "stubbed models are not allowed to access the database"
16
+ end
17
+
18
+ def reload
19
+ raise "stubbed models are not allowed to access the database"
20
+ end
21
+ end
22
+ end
23
+
24
+ def next_id
25
+ @@next_id += 1
26
+ end
27
+
28
+ def get(attribute)
29
+ @stub.send(attribute)
30
+ end
31
+
32
+ def set(attribute, value)
33
+ @stub.send(:"#{attribute}=", value)
34
+ end
35
+
36
+ def associate(name, factory, attributes)
37
+ set(name, Factory.stub(factory, attributes))
38
+ end
39
+
40
+ def association(factory, overrides = {})
41
+ Factory.stub(factory, overrides)
42
+ end
43
+
44
+ def result
45
+ @stub
46
+ end
47
+ end
48
+ end
49
+ end
@@ -0,0 +1,62 @@
1
+ class Factory
2
+
3
+ class Proxy #:nodoc:
4
+ def initialize(klass)
5
+ end
6
+
7
+ def get(attribute)
8
+ nil
9
+ end
10
+
11
+ def set(attribute, value)
12
+ end
13
+
14
+ def associate(name, factory, attributes)
15
+ end
16
+
17
+ # Generates an association using the current build strategy.
18
+ #
19
+ # Arguments:
20
+ # name: (Symbol)
21
+ # The name of the factory that should be used to generate this
22
+ # association.
23
+ # attributes: (Hash)
24
+ # A hash of attributes that should be overridden for this association.
25
+ #
26
+ # Returns:
27
+ # The generated association for the current build strategy. Note that
28
+ # assocaitions are not generated for the attributes_for strategy. Returns
29
+ # nil in this case.
30
+ #
31
+ # Example:
32
+ #
33
+ # Factory.define :user do |f|
34
+ # # ...
35
+ # end
36
+ #
37
+ # Factory.define :post do |f|
38
+ # # ...
39
+ # f.author {|a| a.association :user, :name => 'Joe' }
40
+ # end
41
+ #
42
+ # # Builds (but doesn't save) a Post and a User
43
+ # Factory.build(:post)
44
+ #
45
+ # # Builds and saves a User, builds a Post, assigns the User to the
46
+ # # author association, and saves the User.
47
+ # Factory.create(:post)
48
+ #
49
+ def association(name, overrides = {})
50
+ nil
51
+ end
52
+
53
+ def method_missing(method, *args, &block)
54
+ get(method)
55
+ end
56
+
57
+ def result
58
+ raise NotImplementedError, "Strategies must return a result"
59
+ end
60
+ end
61
+
62
+ end
@@ -0,0 +1,63 @@
1
+ class Factory
2
+
3
+ # Raised when calling Factory.sequence from a dynamic attribute block
4
+ class SequenceAbuseError < StandardError; end
5
+
6
+ # Sequences are defined using Factory.sequence. Sequence values are generated
7
+ # using next.
8
+ class Sequence
9
+
10
+ def initialize (&proc) #:nodoc:
11
+ @proc = proc
12
+ @value = 0
13
+ end
14
+
15
+ # Returns the next value for this sequence
16
+ def next
17
+ @value += 1
18
+ @proc.call(@value)
19
+ end
20
+
21
+ end
22
+
23
+ class << self
24
+ attr_accessor :sequences #:nodoc:
25
+ end
26
+ self.sequences = {}
27
+
28
+ # Defines a new sequence that can be used to generate unique values in a specific format.
29
+ #
30
+ # Arguments:
31
+ # name: (Symbol)
32
+ # A unique name for this sequence. This name will be referenced when
33
+ # calling next to generate new values from this sequence.
34
+ # block: (Proc)
35
+ # The code to generate each value in the sequence. This block will be
36
+ # called with a unique number each time a value in the sequence is to be
37
+ # generated. The block should return the generated value for the
38
+ # sequence.
39
+ #
40
+ # Example:
41
+ #
42
+ # Factory.sequence(:email) {|n| "somebody_#{n}@example.com" }
43
+ def self.sequence (name, &block)
44
+ self.sequences[name] = Sequence.new(&block)
45
+ end
46
+
47
+ # Generates and returns the next value in a sequence.
48
+ #
49
+ # Arguments:
50
+ # name: (Symbol)
51
+ # The name of the sequence that a value should be generated for.
52
+ #
53
+ # Returns:
54
+ # The next value in the sequence. (Object)
55
+ def self.next (sequence)
56
+ unless self.sequences.key?(sequence)
57
+ raise "No such sequence: #{sequence}"
58
+ end
59
+
60
+ self.sequences[sequence].next
61
+ end
62
+
63
+ end
@@ -0,0 +1,42 @@
1
+ class Factory
2
+ module Syntax
3
+
4
+ # Extends ActiveRecord::Base to provide a make class method, which is an
5
+ # alternate syntax for defining factories.
6
+ #
7
+ # Usage:
8
+ #
9
+ # require 'factory_girl/syntax/blueprint'
10
+ #
11
+ # User.blueprint do
12
+ # name { 'Billy Bob' }
13
+ # email { 'billy@bob.example.com' }
14
+ # end
15
+ #
16
+ # Factory(:user, :name => 'Johnny')
17
+ #
18
+ # This syntax was derived from Pete Yandell's machinist.
19
+ module Blueprint
20
+ module ActiveRecord #:nodoc:
21
+
22
+ def self.included(base) # :nodoc:
23
+ base.extend ClassMethods
24
+ end
25
+
26
+ module ClassMethods #:nodoc:
27
+
28
+ def blueprint(&block)
29
+ instance = Factory.new(name.underscore, :class => self)
30
+ instance.instance_eval(&block)
31
+ Factory.factories[instance.factory_name] = instance
32
+ end
33
+
34
+ end
35
+
36
+ end
37
+ end
38
+ end
39
+ end
40
+
41
+ ActiveRecord::Base.send(:include, Factory::Syntax::Blueprint::ActiveRecord)
42
+