ffactory_girl 4.8.1

Sign up to get free protection for your applications and to get access to all the features.
Files changed (83) hide show
  1. checksums.yaml +7 -0
  2. data/.autotest +9 -0
  3. data/.gitignore +9 -0
  4. data/.rspec +2 -0
  5. data/.simplecov +4 -0
  6. data/.travis.yml +38 -0
  7. data/.yardopts +5 -0
  8. data/Appraisals +19 -0
  9. data/CONTRIBUTING.md +60 -0
  10. data/GETTING_STARTED.md +1391 -0
  11. data/Gemfile +8 -0
  12. data/Gemfile.lock +116 -0
  13. data/LICENSE +19 -0
  14. data/NAME.md +11 -0
  15. data/NEWS +290 -0
  16. data/README.md +98 -0
  17. data/Rakefile +36 -0
  18. data/cucumber.yml +1 -0
  19. data/factory_girl.gemspec +36 -0
  20. data/gemfiles/3.2.gemfile +10 -0
  21. data/gemfiles/3.2.gemfile.lock +105 -0
  22. data/gemfiles/4.0.gemfile +10 -0
  23. data/gemfiles/4.0.gemfile.lock +105 -0
  24. data/gemfiles/4.1.gemfile +10 -0
  25. data/gemfiles/4.1.gemfile.lock +104 -0
  26. data/gemfiles/4.2.gemfile +10 -0
  27. data/gemfiles/4.2.gemfile.lock +104 -0
  28. data/gemfiles/5.0.gemfile +10 -0
  29. data/gemfiles/5.0.gemfile.lock +103 -0
  30. data/lib/factory_girl/aliases.rb +18 -0
  31. data/lib/factory_girl/attribute/association.rb +27 -0
  32. data/lib/factory_girl/attribute/dynamic.rb +24 -0
  33. data/lib/factory_girl/attribute/sequence.rb +16 -0
  34. data/lib/factory_girl/attribute/static.rb +16 -0
  35. data/lib/factory_girl/attribute.rb +62 -0
  36. data/lib/factory_girl/attribute_assigner.rb +97 -0
  37. data/lib/factory_girl/attribute_list.rb +67 -0
  38. data/lib/factory_girl/callback.rb +40 -0
  39. data/lib/factory_girl/callbacks_observer.rb +21 -0
  40. data/lib/factory_girl/configuration.rb +37 -0
  41. data/lib/factory_girl/declaration/association.rb +28 -0
  42. data/lib/factory_girl/declaration/dynamic.rb +26 -0
  43. data/lib/factory_girl/declaration/implicit.rb +33 -0
  44. data/lib/factory_girl/declaration/static.rb +26 -0
  45. data/lib/factory_girl/declaration.rb +23 -0
  46. data/lib/factory_girl/declaration_list.rb +49 -0
  47. data/lib/factory_girl/decorator/attribute_hash.rb +16 -0
  48. data/lib/factory_girl/decorator/class_key_hash.rb +28 -0
  49. data/lib/factory_girl/decorator/disallows_duplicates_registry.rb +13 -0
  50. data/lib/factory_girl/decorator/invocation_tracker.rb +19 -0
  51. data/lib/factory_girl/decorator/new_constructor.rb +12 -0
  52. data/lib/factory_girl/decorator.rb +21 -0
  53. data/lib/factory_girl/definition.rb +136 -0
  54. data/lib/factory_girl/definition_hierarchy.rb +48 -0
  55. data/lib/factory_girl/definition_proxy.rb +174 -0
  56. data/lib/factory_girl/errors.rb +25 -0
  57. data/lib/factory_girl/evaluation.rb +27 -0
  58. data/lib/factory_girl/evaluator.rb +82 -0
  59. data/lib/factory_girl/evaluator_class_definer.rb +20 -0
  60. data/lib/factory_girl/factory.rb +163 -0
  61. data/lib/factory_girl/factory_runner.rb +33 -0
  62. data/lib/factory_girl/find_definitions.rb +25 -0
  63. data/lib/factory_girl/linter.rb +97 -0
  64. data/lib/factory_girl/null_factory.rb +18 -0
  65. data/lib/factory_girl/null_object.rb +24 -0
  66. data/lib/factory_girl/registry.rb +38 -0
  67. data/lib/factory_girl/reload.rb +8 -0
  68. data/lib/factory_girl/sequence.rb +62 -0
  69. data/lib/factory_girl/strategy/attributes_for.rb +13 -0
  70. data/lib/factory_girl/strategy/build.rb +15 -0
  71. data/lib/factory_girl/strategy/create.rb +18 -0
  72. data/lib/factory_girl/strategy/null.rb +11 -0
  73. data/lib/factory_girl/strategy/stub.rb +111 -0
  74. data/lib/factory_girl/strategy_calculator.rb +26 -0
  75. data/lib/factory_girl/strategy_syntax_method_registrar.rb +54 -0
  76. data/lib/factory_girl/syntax/default.rb +76 -0
  77. data/lib/factory_girl/syntax/methods.rb +111 -0
  78. data/lib/factory_girl/syntax.rb +7 -0
  79. data/lib/factory_girl/syntax_runner.rb +6 -0
  80. data/lib/factory_girl/trait.rb +30 -0
  81. data/lib/factory_girl/version.rb +3 -0
  82. data/lib/factory_girl.rb +156 -0
  83. metadata +271 -0
@@ -0,0 +1,1391 @@
1
+ Getting Started
2
+ ===============
3
+
4
+ Update Your Gemfile
5
+ -------------------
6
+
7
+ If you're using Rails, you'll need to change the required version of `factory_girl_rails`:
8
+
9
+ ```ruby
10
+ gem "factory_girl_rails", "~> 4.0"
11
+ ```
12
+
13
+ If you're *not* using Rails, you'll just have to change the required version of `factory_girl`:
14
+
15
+ ```ruby
16
+ gem "factory_girl", "~> 4.0"
17
+ ```
18
+
19
+ JRuby users: factory_girl works with JRuby starting with 1.6.7.2 (latest stable, as per July 2012).
20
+ JRuby has to be used in 1.9 mode, for that, use JRUBY_OPTS environment variable:
21
+
22
+ ```bash
23
+ export JRUBY_OPTS=--1.9
24
+ ```
25
+
26
+ Once your Gemfile is updated, you'll want to update your bundle.
27
+
28
+ Configure your test suite
29
+ -------------------------
30
+
31
+ # RSpec
32
+
33
+ ```ruby
34
+ # spec/support/factory_girl.rb
35
+ RSpec.configure do |config|
36
+ config.include FactoryGirl::Syntax::Methods
37
+ end
38
+
39
+ # RSpec without Rails
40
+ RSpec.configure do |config|
41
+ config.include FactoryGirl::Syntax::Methods
42
+
43
+ config.before(:suite) do
44
+ FactoryGirl.find_definitions
45
+ end
46
+ end
47
+ ```
48
+
49
+ Remember to require the above file in your rails_helper since the support folder isn't eagerly loaded
50
+
51
+ ```ruby
52
+ require 'support/factory_girl'
53
+ ```
54
+
55
+ # Test::Unit
56
+
57
+ ```ruby
58
+ class Test::Unit::TestCase
59
+ include FactoryGirl::Syntax::Methods
60
+ end
61
+ ```
62
+
63
+ # Cucumber
64
+
65
+ ```ruby
66
+ # env.rb (Rails example location - RAILS_ROOT/features/support/env.rb)
67
+ World(FactoryGirl::Syntax::Methods)
68
+ ```
69
+
70
+ # Spinach
71
+
72
+ ```ruby
73
+ class Spinach::FeatureSteps
74
+ include FactoryGirl::Syntax::Methods
75
+ end
76
+ ```
77
+
78
+ # Minitest
79
+
80
+ ```ruby
81
+ class Minitest::Unit::TestCase
82
+ include FactoryGirl::Syntax::Methods
83
+ end
84
+ ```
85
+
86
+ # Minitest::Spec
87
+
88
+ ```ruby
89
+ class Minitest::Spec
90
+ include FactoryGirl::Syntax::Methods
91
+ end
92
+ ```
93
+
94
+ # minitest-rails
95
+
96
+ ```ruby
97
+ class ActiveSupport::TestCase
98
+ include FactoryGirl::Syntax::Methods
99
+ end
100
+ ```
101
+
102
+ If you do not include `FactoryGirl::Syntax::Methods` in your test suite, then all factory_girl methods will need to be prefaced with `FactoryGirl`.
103
+
104
+ Defining factories
105
+ ------------------
106
+
107
+ Each factory has a name and a set of attributes. The name is used to guess the class of the object by default, but it's possible to explicitly specify it:
108
+
109
+ ```ruby
110
+ # This will guess the User class
111
+ FactoryGirl.define do
112
+ factory :user do
113
+ first_name "John"
114
+ last_name "Doe"
115
+ admin false
116
+ end
117
+
118
+ # This will use the User class (Admin would have been guessed)
119
+ factory :admin, class: User do
120
+ first_name "Admin"
121
+ last_name "User"
122
+ admin true
123
+ end
124
+ end
125
+ ```
126
+
127
+ It is highly recommended that you have one factory for each class that provides the simplest set of attributes necessary to create an instance of that class. If you're creating ActiveRecord objects, that means that you should only provide attributes that are required through validations and that do not have defaults. Other factories can be created through inheritance to cover common scenarios for each class.
128
+
129
+ Attempting to define multiple factories with the same name will raise an error.
130
+
131
+ Factories can be defined anywhere, but will be automatically loaded after
132
+ calling `FactoryGirl.find_definitions` if factories are defined in files at the
133
+ following locations:
134
+
135
+ test/factories.rb
136
+ spec/factories.rb
137
+ test/factories/*.rb
138
+ spec/factories/*.rb
139
+
140
+ Using factories
141
+ ---------------
142
+
143
+ factory\_girl supports several different build strategies: build, create, attributes\_for and build\_stubbed:
144
+
145
+ ```ruby
146
+ # Returns a User instance that's not saved
147
+ user = build(:user)
148
+
149
+ # Returns a saved User instance
150
+ user = create(:user)
151
+
152
+ # Returns a hash of attributes that can be used to build a User instance
153
+ attrs = attributes_for(:user)
154
+
155
+ # Returns an object with all defined attributes stubbed out
156
+ stub = build_stubbed(:user)
157
+
158
+ # Passing a block to any of the methods above will yield the return object
159
+ create(:user) do |user|
160
+ user.posts.create(attributes_for(:post))
161
+ end
162
+ ```
163
+
164
+ No matter which strategy is used, it's possible to override the defined attributes by passing a hash:
165
+
166
+ ```ruby
167
+ # Build a User instance and override the first_name property
168
+ user = build(:user, first_name: "Joe")
169
+ user.first_name
170
+ # => "Joe"
171
+ ```
172
+
173
+ Dynamic Attributes
174
+ ------------------
175
+
176
+ Most factory attributes can be added using static values that are evaluated when
177
+ the factory is defined, but some attributes (such as associations and other
178
+ attributes that must be dynamically generated) will need values assigned each
179
+ time an instance is generated. These "dynamic" attributes can be added by passing a
180
+ block instead of a parameter:
181
+
182
+ ```ruby
183
+ factory :user do
184
+ # ...
185
+ activation_code { User.generate_activation_code }
186
+ date_of_birth { 21.years.ago }
187
+ end
188
+ ```
189
+
190
+ Because of the block syntax in Ruby, defining attributes as `Hash`es (for
191
+ serialized/JSON columns, for example) requires two sets of curly brackets:
192
+
193
+ ```ruby
194
+ factory :program do
195
+ configuration { { auto_resolve: false, auto_define: true } }
196
+ end
197
+ ```
198
+
199
+ Aliases
200
+ -------
201
+ factory_girl allows you to define aliases to existing factories to make them easier to re-use. This could come in handy when, for example, your Post object has an author attribute that actually refers to an instance of a User class. While normally factory_girl can infer the factory name from the association name, in this case it will look for a author factory in vain. So, alias your user factory so it can be used under alias names.
202
+
203
+ ```ruby
204
+ factory :user, aliases: [:author, :commenter] do
205
+ first_name "John"
206
+ last_name "Doe"
207
+ date_of_birth { 18.years.ago }
208
+ end
209
+
210
+ factory :post do
211
+ author
212
+ # instead of
213
+ # association :author, factory: :user
214
+ title "How to read a book effectively"
215
+ body "There are five steps involved."
216
+ end
217
+
218
+ factory :comment do
219
+ commenter
220
+ # instead of
221
+ # association :commenter, factory: :user
222
+ body "Great article!"
223
+ end
224
+ ```
225
+
226
+ Dependent Attributes
227
+ --------------------
228
+
229
+ Attributes can be based on the values of other attributes using the evaluator
230
+ that is yielded to dynamic attribute blocks:
231
+
232
+ ```ruby
233
+ factory :user do
234
+ first_name "Joe"
235
+ last_name "Blow"
236
+ email { "#{first_name}.#{last_name}@example.com".downcase }
237
+ end
238
+
239
+ create(:user, last_name: "Doe").email
240
+ # => "joe.doe@example.com"
241
+ ```
242
+
243
+ Transient Attributes
244
+ --------------------
245
+
246
+ There may be times where your code can be DRYed up by passing in transient attributes to factories.
247
+
248
+ ```ruby
249
+ factory :user do
250
+ transient do
251
+ rockstar true
252
+ upcased false
253
+ end
254
+
255
+ name { "John Doe#{" - Rockstar" if rockstar}" }
256
+ email { "#{name.downcase}@example.com" }
257
+
258
+ after(:create) do |user, evaluator|
259
+ user.name.upcase! if evaluator.upcased
260
+ end
261
+ end
262
+
263
+ create(:user, upcased: true).name
264
+ #=> "JOHN DOE - ROCKSTAR"
265
+ ```
266
+
267
+ Static and dynamic attributes can be created as transient attributes. Transient
268
+ attributes will be ignored within attributes\_for and won't be set on the model,
269
+ even if the attribute exists or you attempt to override it.
270
+
271
+ Within factory_girl's dynamic attributes, you can access transient attributes as
272
+ you would expect. If you need to access the evaluator in a factory_girl callback,
273
+ you'll need to declare a second block argument (for the evaluator) and access
274
+ transient attributes from there.
275
+
276
+ Method Name / Reserved Word Attributes
277
+ -------------------------------
278
+
279
+ If your attributes conflict with existing methods or reserved words you can define them with `add_attribute`.
280
+
281
+ ```ruby
282
+ factory :dna do
283
+ add_attribute(:sequence) { 'GATTACA' }
284
+ end
285
+
286
+ factory :payment do
287
+ add_attribute(:method) { 'paypal' }
288
+ end
289
+
290
+ ```
291
+
292
+ Inheritance
293
+ -----------
294
+
295
+ You can easily create multiple factories for the same class without repeating common attributes by nesting factories:
296
+
297
+ ```ruby
298
+ factory :post do
299
+ title "A title"
300
+
301
+ factory :approved_post do
302
+ approved true
303
+ end
304
+ end
305
+
306
+ approved_post = create(:approved_post)
307
+ approved_post.title # => "A title"
308
+ approved_post.approved # => true
309
+ ```
310
+
311
+ You can also assign the parent explicitly:
312
+
313
+ ```ruby
314
+ factory :post do
315
+ title "A title"
316
+ end
317
+
318
+ factory :approved_post, parent: :post do
319
+ approved true
320
+ end
321
+ ```
322
+
323
+ As mentioned above, it's good practice to define a basic factory for each class
324
+ with only the attributes required to create it. Then, create more specific
325
+ factories that inherit from this basic parent. Factory definitions are still
326
+ code, so keep them DRY.
327
+
328
+ Associations
329
+ ------------
330
+
331
+ It's possible to set up associations within factories. If the factory name is the same as the association name, the factory name can be left out.
332
+
333
+ ```ruby
334
+ factory :post do
335
+ # ...
336
+ author
337
+ end
338
+ ```
339
+
340
+ You can also specify a different factory or override attributes:
341
+
342
+ ```ruby
343
+ factory :post do
344
+ # ...
345
+ association :author, factory: :user, last_name: "Writely"
346
+ end
347
+ ```
348
+
349
+ The behavior of the association method varies depending on the build strategy used for the parent object.
350
+
351
+ ```ruby
352
+ # Builds and saves a User and a Post
353
+ post = create(:post)
354
+ post.new_record? # => false
355
+ post.author.new_record? # => false
356
+
357
+ # Builds and saves a User, and then builds but does not save a Post
358
+ post = build(:post)
359
+ post.new_record? # => true
360
+ post.author.new_record? # => false
361
+ ```
362
+
363
+ To not save the associated object, specify strategy: :build in the factory:
364
+
365
+ ```ruby
366
+ factory :post do
367
+ # ...
368
+ association :author, factory: :user, strategy: :build
369
+ end
370
+
371
+ # Builds a User, and then builds a Post, but does not save either
372
+ post = build(:post)
373
+ post.new_record? # => true
374
+ post.author.new_record? # => true
375
+ ```
376
+
377
+ Please note that the `strategy: :build` option must be passed to an explicit call to `association`,
378
+ and cannot be used with implicit associations:
379
+
380
+ ```ruby
381
+ factory :post do
382
+ # ...
383
+ author strategy: :build # <<< this does *not* work; causes author_id to be nil
384
+ ```
385
+
386
+ Generating data for a `has_many` relationship is a bit more involved,
387
+ depending on the amount of flexibility desired, but here's a surefire example
388
+ of generating associated data.
389
+
390
+ ```ruby
391
+ FactoryGirl.define do
392
+
393
+ # post factory with a `belongs_to` association for the user
394
+ factory :post do
395
+ title "Through the Looking Glass"
396
+ user
397
+ end
398
+
399
+ # user factory without associated posts
400
+ factory :user do
401
+ name "John Doe"
402
+
403
+ # user_with_posts will create post data after the user has been created
404
+ factory :user_with_posts do
405
+ # posts_count is declared as a transient attribute and available in
406
+ # attributes on the factory, as well as the callback via the evaluator
407
+ transient do
408
+ posts_count 5
409
+ end
410
+
411
+ # the after(:create) yields two values; the user instance itself and the
412
+ # evaluator, which stores all values from the factory, including transient
413
+ # attributes; `create_list`'s second argument is the number of records
414
+ # to create and we make sure the user is associated properly to the post
415
+ after(:create) do |user, evaluator|
416
+ create_list(:post, evaluator.posts_count, user: user)
417
+ end
418
+ end
419
+ end
420
+ end
421
+ ```
422
+
423
+ This allows us to do:
424
+
425
+ ```ruby
426
+ create(:user).posts.length # 0
427
+ create(:user_with_posts).posts.length # 5
428
+ create(:user_with_posts, posts_count: 15).posts.length # 15
429
+ ```
430
+
431
+ Generating data for a `has_and_belongs_to_many` relationship is very similar
432
+ to the above `has_many` relationship, with a small change, you need to pass an
433
+ array of objects to the model's pluralized attribute name rather than a single
434
+ object to the singular version of the attribute name.
435
+
436
+ Here's an example with two models that are related via
437
+ `has_and_belongs_to_many`:
438
+
439
+ ```ruby
440
+ FactoryGirl.define do
441
+
442
+ # language factory with a `belongs_to` association for the profile
443
+ factory :language do
444
+ title "Through the Looking Glass"
445
+ profile
446
+ end
447
+
448
+ # profile factory without associated languages
449
+ factory :profile do
450
+ name "John Doe"
451
+
452
+ # profile_with_languages will create language data after the profile has
453
+ # been created
454
+ factory :profile_with_languages do
455
+ # languages_count is declared as an ignored attribute and available in
456
+ # attributes on the factory, as well as the callback via the evaluator
457
+ transient do
458
+ languages_count 5
459
+ end
460
+
461
+ # the after(:create) yields two values; the profile instance itself and
462
+ # the evaluator, which stores all values from the factory, including
463
+ # ignored attributes; `create_list`'s second argument is the number of
464
+ # records to create and we make sure the profile is associated properly
465
+ # to the language
466
+ after(:create) do |profile, evaluator|
467
+ create_list(:language, evaluator.languages_count, profiles: [profile])
468
+ end
469
+ end
470
+ end
471
+ end
472
+ ```
473
+
474
+ This allows us to do:
475
+
476
+ ```ruby
477
+ create(:profile).languages.length # 0
478
+ create(:profile_with_languages).languages.length # 5
479
+ create(:profile_with_languages, languages_count: 15).languages.length # 15
480
+ ```
481
+
482
+ Sequences
483
+ ---------
484
+
485
+ Unique values in a specific format (for example, e-mail addresses) can be
486
+ generated using sequences. Sequences are defined by calling `sequence` in a
487
+ definition block, and values in a sequence are generated by calling
488
+ `generate`:
489
+
490
+ ```ruby
491
+ # Defines a new sequence
492
+ FactoryGirl.define do
493
+ sequence :email do |n|
494
+ "person#{n}@example.com"
495
+ end
496
+ end
497
+
498
+ generate :email
499
+ # => "person1@example.com"
500
+
501
+ generate :email
502
+ # => "person2@example.com"
503
+ ```
504
+
505
+ Sequences can be used in dynamic attributes:
506
+
507
+ ```ruby
508
+ factory :invite do
509
+ invitee { generate(:email) }
510
+ end
511
+ ```
512
+
513
+ Or as implicit attributes:
514
+
515
+ ```ruby
516
+ factory :user do
517
+ email # Same as `email { generate(:email) }`
518
+ end
519
+ ```
520
+
521
+ And it's also possible to define an in-line sequence that is only used in
522
+ a particular factory:
523
+
524
+ ```ruby
525
+ factory :user do
526
+ sequence(:email) { |n| "person#{n}@example.com" }
527
+ end
528
+ ```
529
+
530
+ You can also override the initial value:
531
+
532
+ ```ruby
533
+ factory :user do
534
+ sequence(:email, 1000) { |n| "person#{n}@example.com" }
535
+ end
536
+ ```
537
+
538
+ Without a block, the value will increment itself, starting at its initial value:
539
+
540
+ ```ruby
541
+ factory :post do
542
+ sequence(:position)
543
+ end
544
+ ```
545
+
546
+ Sequences can also have aliases. The sequence aliases share the same counter:
547
+
548
+ ```ruby
549
+ factory :user do
550
+ sequence(:email, 1000, aliases: [:sender, :receiver]) { |n| "person#{n}@example.com" }
551
+ end
552
+
553
+ # will increase value counter for :email which is shared by :sender and :receiver
554
+ generate(:sender)
555
+ ```
556
+
557
+ Define aliases and use default value (1) for the counter
558
+
559
+ ```ruby
560
+ factory :user do
561
+ sequence(:email, aliases: [:sender, :receiver]) { |n| "person#{n}@example.com" }
562
+ end
563
+ ```
564
+
565
+ Setting the value:
566
+
567
+ ```ruby
568
+ factory :user do
569
+ sequence(:email, 'a', aliases: [:sender, :receiver]) { |n| "person#{n}@example.com" }
570
+ end
571
+ ```
572
+
573
+ The value just needs to support the `#next` method. Here the next value will be 'a', then 'b', etc.
574
+
575
+ Traits
576
+ ------
577
+
578
+ Traits allow you to group attributes together and then apply them
579
+ to any factory.
580
+
581
+ ```ruby
582
+ factory :user, aliases: [:author]
583
+
584
+ factory :story do
585
+ title "My awesome story"
586
+ author
587
+
588
+ trait :published do
589
+ published true
590
+ end
591
+
592
+ trait :unpublished do
593
+ published false
594
+ end
595
+
596
+ trait :week_long_publishing do
597
+ start_at { 1.week.ago }
598
+ end_at { Time.now }
599
+ end
600
+
601
+ trait :month_long_publishing do
602
+ start_at { 1.month.ago }
603
+ end_at { Time.now }
604
+ end
605
+
606
+ factory :week_long_published_story, traits: [:published, :week_long_publishing]
607
+ factory :month_long_published_story, traits: [:published, :month_long_publishing]
608
+ factory :week_long_unpublished_story, traits: [:unpublished, :week_long_publishing]
609
+ factory :month_long_unpublished_story, traits: [:unpublished, :month_long_publishing]
610
+ end
611
+ ```
612
+
613
+ Traits can be used as attributes:
614
+
615
+ ```ruby
616
+ factory :week_long_published_story_with_title, parent: :story do
617
+ published
618
+ week_long_publishing
619
+ title { "Publishing that was started at #{start_at}" }
620
+ end
621
+ ```
622
+
623
+ Traits that define the same attributes won't raise AttributeDefinitionErrors;
624
+ the trait that defines the attribute latest gets precedence.
625
+
626
+ ```ruby
627
+ factory :user do
628
+ name "Friendly User"
629
+ login { name }
630
+
631
+ trait :male do
632
+ name "John Doe"
633
+ gender "Male"
634
+ login { "#{name} (M)" }
635
+ end
636
+
637
+ trait :female do
638
+ name "Jane Doe"
639
+ gender "Female"
640
+ login { "#{name} (F)" }
641
+ end
642
+
643
+ trait :admin do
644
+ admin true
645
+ login { "admin-#{name}" }
646
+ end
647
+
648
+ factory :male_admin, traits: [:male, :admin] # login will be "admin-John Doe"
649
+ factory :female_admin, traits: [:admin, :female] # login will be "Jane Doe (F)"
650
+ end
651
+ ```
652
+
653
+ You can also override individual attributes granted by a trait in subclasses.
654
+
655
+ ```ruby
656
+ factory :user do
657
+ name "Friendly User"
658
+ login { name }
659
+
660
+ trait :male do
661
+ name "John Doe"
662
+ gender "Male"
663
+ login { "#{name} (M)" }
664
+ end
665
+
666
+ factory :brandon do
667
+ male
668
+ name "Brandon"
669
+ end
670
+ end
671
+ ```
672
+
673
+ Traits can also be passed in as a list of symbols when you construct an instance from factory_girl.
674
+
675
+ ```ruby
676
+ factory :user do
677
+ name "Friendly User"
678
+
679
+ trait :male do
680
+ name "John Doe"
681
+ gender "Male"
682
+ end
683
+
684
+ trait :admin do
685
+ admin true
686
+ end
687
+ end
688
+
689
+ # creates an admin user with gender "Male" and name "Jon Snow"
690
+ create(:user, :admin, :male, name: "Jon Snow")
691
+ ```
692
+
693
+ This ability works with `build`, `build_stubbed`, `attributes_for`, and `create`.
694
+
695
+ `create_list` and `build_list` methods are supported as well. Just remember to pass
696
+ the number of instances to create/build as second parameter, as documented in the
697
+ "Building or Creating Multiple Records" section of this file.
698
+
699
+ ```ruby
700
+ factory :user do
701
+ name "Friendly User"
702
+
703
+ trait :admin do
704
+ admin true
705
+ end
706
+ end
707
+
708
+ # creates 3 admin users with gender "Male" and name "Jon Snow"
709
+ create_list(:user, 3, :admin, :male, name: "Jon Snow")
710
+ ```
711
+
712
+ Traits can be used with associations easily too:
713
+
714
+ ```ruby
715
+ factory :user do
716
+ name "Friendly User"
717
+
718
+ trait :admin do
719
+ admin true
720
+ end
721
+ end
722
+
723
+ factory :post do
724
+ association :user, :admin, name: 'John Doe'
725
+ end
726
+
727
+ # creates an admin user with name "John Doe"
728
+ create(:post).user
729
+ ```
730
+
731
+ When you're using association names that're different than the factory:
732
+
733
+ ```ruby
734
+ factory :user do
735
+ name "Friendly User"
736
+
737
+ trait :admin do
738
+ admin true
739
+ end
740
+ end
741
+
742
+ factory :post do
743
+ association :author, :admin, factory: :user, name: 'John Doe'
744
+ # or
745
+ association :author, factory: [:user, :admin], name: 'John Doe'
746
+ end
747
+
748
+ # creates an admin user with name "John Doe"
749
+ create(:post).author
750
+ ```
751
+
752
+ Traits can be used within other traits to mix in their attributes.
753
+
754
+ ```ruby
755
+ factory :order do
756
+ trait :completed do
757
+ completed_at { 3.days.ago }
758
+ end
759
+
760
+ trait :refunded do
761
+ completed
762
+ refunded_at { 1.day.ago }
763
+ end
764
+ end
765
+ ```
766
+
767
+ Finally, traits can accept transient attributes.
768
+
769
+ ```ruby
770
+ factory :invoice do
771
+ trait :with_amount do
772
+ transient do
773
+ amount 1
774
+ end
775
+
776
+ after(:create) do |invoice, evaluator|
777
+ create :line_item, invoice: invoice, amount: evaluator.amount
778
+ end
779
+ end
780
+ end
781
+
782
+ create :invoice, :with_amount, amount: 2
783
+ ```
784
+
785
+ Callbacks
786
+ ---------
787
+
788
+ factory\_girl makes available four callbacks for injecting some code:
789
+
790
+ * after(:build) - called after a factory is built (via `FactoryGirl.build`, `FactoryGirl.create`)
791
+ * before(:create) - called before a factory is saved (via `FactoryGirl.create`)
792
+ * after(:create) - called after a factory is saved (via `FactoryGirl.create`)
793
+ * after(:stub) - called after a factory is stubbed (via `FactoryGirl.build_stubbed`)
794
+
795
+ Examples:
796
+
797
+ ```ruby
798
+ # Define a factory that calls the generate_hashed_password method after it is built
799
+ factory :user do
800
+ after(:build) { |user| generate_hashed_password(user) }
801
+ end
802
+ ```
803
+
804
+ Note that you'll have an instance of the user in the block. This can be useful.
805
+
806
+ You can also define multiple types of callbacks on the same factory:
807
+
808
+ ```ruby
809
+ factory :user do
810
+ after(:build) { |user| do_something_to(user) }
811
+ after(:create) { |user| do_something_else_to(user) }
812
+ end
813
+ ```
814
+
815
+ Factories can also define any number of the same kind of callback. These callbacks will be executed in the order they are specified:
816
+
817
+ ```ruby
818
+ factory :user do
819
+ after(:create) { this_runs_first }
820
+ after(:create) { then_this }
821
+ end
822
+ ```
823
+
824
+ Calling `create` will invoke both `after_build` and `after_create` callbacks.
825
+
826
+ Also, like standard attributes, child factories will inherit (and can also define) callbacks from their parent factory.
827
+
828
+ Multiple callbacks can be assigned to run a block; this is useful when building various strategies that run the same code (since there are no callbacks that are shared across all strategies).
829
+
830
+ ```ruby
831
+ factory :user do
832
+ callback(:after_stub, :before_create) { do_something }
833
+ after(:stub, :create) { do_something_else }
834
+ before(:create, :custom) { do_a_third_thing }
835
+ end
836
+ ```
837
+
838
+ To override callbacks for all factories, define them within the
839
+ `FactoryGirl.define` block:
840
+
841
+ ```ruby
842
+ FactoryGirl.define do
843
+ after(:build) { |object| puts "Built #{object}" }
844
+ after(:create) { |object| AuditLog.create(attrs: object.attributes) }
845
+
846
+ factory :user do
847
+ name "John Doe"
848
+ end
849
+ end
850
+ ```
851
+
852
+ You can also call callbacks that rely on `Symbol#to_proc`:
853
+
854
+ ```ruby
855
+ # app/models/user.rb
856
+ class User < ActiveRecord::Base
857
+ def confirm!
858
+ # confirm the user account
859
+ end
860
+ end
861
+
862
+ # spec/factories.rb
863
+ FactoryGirl.define do
864
+ factory :user do
865
+ after :create, &:confirm!
866
+ end
867
+ end
868
+
869
+ create(:user) # creates the user and confirms it
870
+ ```
871
+
872
+ Modifying factories
873
+ -------------------
874
+
875
+ If you're given a set of factories (say, from a gem developer) but want to change them to fit into your application better, you can
876
+ modify that factory instead of creating a child factory and adding attributes there.
877
+
878
+ If a gem were to give you a User factory:
879
+
880
+ ```ruby
881
+ FactoryGirl.define do
882
+ factory :user do
883
+ full_name "John Doe"
884
+ sequence(:username) { |n| "user#{n}" }
885
+ password "password"
886
+ end
887
+ end
888
+ ```
889
+
890
+ Instead of creating a child factory that added additional attributes:
891
+
892
+ ```ruby
893
+ FactoryGirl.define do
894
+ factory :application_user, parent: :user do
895
+ full_name "Jane Doe"
896
+ date_of_birth { 21.years.ago }
897
+ gender "Female"
898
+ health 90
899
+ end
900
+ end
901
+ ```
902
+
903
+ You could modify that factory instead.
904
+
905
+ ```ruby
906
+ FactoryGirl.modify do
907
+ factory :user do
908
+ full_name "Jane Doe"
909
+ date_of_birth { 21.years.ago }
910
+ gender "Female"
911
+ health 90
912
+ end
913
+ end
914
+ ```
915
+
916
+ When modifying a factory, you can change any of the attributes you want (aside from callbacks).
917
+
918
+ `FactoryGirl.modify` must be called outside of a `FactoryGirl.define` block as it operates on factories differently.
919
+
920
+ A caveat: you can only modify factories (not sequences or traits) and callbacks *still compound as they normally would*. So, if
921
+ the factory you're modifying defines an `after(:create)` callback, you defining an `after(:create)` won't override it, it'll just get run after the first callback.
922
+
923
+ Building or Creating Multiple Records
924
+ -------------------------------------
925
+
926
+ Sometimes, you'll want to create or build multiple instances of a factory at once.
927
+
928
+ ```ruby
929
+ built_users = build_list(:user, 25)
930
+ created_users = create_list(:user, 25)
931
+ ```
932
+
933
+ These methods will build or create a specific amount of factories and return them as an array.
934
+ To set the attributes for each of the factories, you can pass in a hash as you normally would.
935
+
936
+ ```ruby
937
+ twenty_year_olds = build_list(:user, 25, date_of_birth: 20.years.ago)
938
+ ```
939
+
940
+ `build_stubbed_list` will give you fully stubbed out instances:
941
+
942
+ ```ruby
943
+ stubbed_users = build_stubbed_list(:user, 25) # array of stubbed users
944
+ ```
945
+
946
+ There's also a set of `*_pair` methods for creating two records at a time:
947
+
948
+ ```ruby
949
+ built_users = build_pair(:user) # array of two built users
950
+ created_users = create_pair(:user) # array of two created users
951
+ ```
952
+
953
+ If you need multiple attribute hashes, `attributes_for_list` will generate them:
954
+
955
+ ```ruby
956
+ users_attrs = attributes_for_list(:user, 25) # array of attribute hashes
957
+ ```
958
+
959
+ Linting Factories
960
+ -----------------
961
+
962
+ factory_girl allows for linting known factories:
963
+
964
+ ```ruby
965
+ FactoryGirl.lint
966
+ ```
967
+
968
+ `FactoryGirl.lint` creates each factory and catches any exceptions raised
969
+ during the creation process. `FactoryGirl::InvalidFactoryError` is raised with
970
+ a list of factories (and corresponding exceptions) for factories which could
971
+ not be created.
972
+
973
+ Recommended usage of `FactoryGirl.lint`
974
+ is to run this in a task
975
+ before your test suite is executed.
976
+ Running it in a `before(:suite)`,
977
+ will negatively impact the performance
978
+ of your tests
979
+ when running single tests.
980
+
981
+ Example Rake task:
982
+
983
+ ```ruby
984
+ # lib/tasks/factory_girl.rake
985
+ namespace :factory_girl do
986
+ desc "Verify that all FactoryGirl factories are valid"
987
+ task lint: :environment do
988
+ if Rails.env.test?
989
+ DatabaseCleaner.cleaning do
990
+ FactoryGirl.lint
991
+ end
992
+ else
993
+ system("bundle exec rake factory_girl:lint RAILS_ENV='test'")
994
+ exit $?.exitstatus
995
+ end
996
+ end
997
+ end
998
+ ```
999
+
1000
+ After calling `FactoryGirl.lint`, you'll likely want to clear out the
1001
+ database, as records will most likely be created. The provided example above
1002
+ uses the database_cleaner gem to clear out the database; be sure to add the
1003
+ gem to your Gemfile under the appropriate groups.
1004
+
1005
+ You can lint factories selectively by passing only factories you want linted:
1006
+
1007
+ ```ruby
1008
+ factories_to_lint = FactoryGirl.factories.reject do |factory|
1009
+ factory.name =~ /^old_/
1010
+ end
1011
+
1012
+ FactoryGirl.lint factories_to_lint
1013
+ ```
1014
+
1015
+ This would lint all factories that aren't prefixed with `old_`.
1016
+
1017
+ Traits can also be linted. This option verifies that each
1018
+ and every trait of a factory generates a valid object on its own.
1019
+ This is turned on by passing `traits: true` to the `lint` method:
1020
+
1021
+ ```ruby
1022
+ FactoryGirl.lint traits: true
1023
+ ```
1024
+
1025
+ This can also be combined with other arguments:
1026
+
1027
+ ```ruby
1028
+ FactoryGirl.lint factories_to_lint, traits: true
1029
+ ```
1030
+
1031
+ You can also specify the strategy used for linting:
1032
+
1033
+ ```ruby
1034
+ FactoryGirl.lint strategy: :build
1035
+ ```
1036
+
1037
+ Custom Construction
1038
+ -------------------
1039
+
1040
+ If you want to use factory_girl to construct an object where some attributes
1041
+ are passed to `initialize` or if you want to do something other than simply
1042
+ calling `new` on your build class, you can override the default behavior by
1043
+ defining `initialize_with` on your factory. Example:
1044
+
1045
+ ```ruby
1046
+ # user.rb
1047
+ class User
1048
+ attr_accessor :name, :email
1049
+
1050
+ def initialize(name)
1051
+ @name = name
1052
+ end
1053
+ end
1054
+
1055
+ # factories.rb
1056
+ sequence(:email) { |n| "person#{n}@example.com" }
1057
+
1058
+ factory :user do
1059
+ name "Jane Doe"
1060
+ email
1061
+
1062
+ initialize_with { new(name) }
1063
+ end
1064
+
1065
+ build(:user).name # Jane Doe
1066
+ ```
1067
+
1068
+ Although factory_girl is written to work with ActiveRecord out of the box, it
1069
+ can also work with any Ruby class. For maximum compatibility with ActiveRecord,
1070
+ the default initializer builds all instances by calling `new` on your build class
1071
+ without any arguments. It then calls attribute writer methods to assign all the
1072
+ attribute values. While that works fine for ActiveRecord, it actually doesn't
1073
+ work for almost any other Ruby class.
1074
+
1075
+ You can override the initializer in order to:
1076
+
1077
+ * Build non-ActiveRecord objects that require arguments to `initialize`
1078
+ * Use a method other than `new` to instantiate the instance
1079
+ * Do crazy things like decorate the instance after it's built
1080
+
1081
+ When using `initialize_with`, you don't have to declare the class itself when
1082
+ calling `new`; however, any other class methods you want to call will have to
1083
+ be called on the class explicitly.
1084
+
1085
+ For example:
1086
+
1087
+ ```ruby
1088
+ factory :user do
1089
+ name "John Doe"
1090
+
1091
+ initialize_with { User.build_with_name(name) }
1092
+ end
1093
+ ```
1094
+
1095
+ You can also access all public attributes within the `initialize_with` block
1096
+ by calling `attributes`:
1097
+
1098
+ ```ruby
1099
+ factory :user do
1100
+ transient do
1101
+ comments_count 5
1102
+ end
1103
+
1104
+ name "John Doe"
1105
+
1106
+ initialize_with { new(attributes) }
1107
+ end
1108
+ ```
1109
+
1110
+ This will build a hash of all attributes to be passed to `new`. It won't
1111
+ include transient attributes, but everything else defined in the factory will be
1112
+ passed (associations, evalued sequences, etc.)
1113
+
1114
+ You can define `initialize_with` for all factories by including it in the
1115
+ `FactoryGirl.define` block:
1116
+
1117
+ ```ruby
1118
+ FactoryGirl.define do
1119
+ initialize_with { new("Awesome first argument") }
1120
+ end
1121
+ ```
1122
+
1123
+ When using `initialize_with`, attributes accessed from within the `initialize_with`
1124
+ block are assigned *only* in the constructor; this equates to roughly the
1125
+ following code:
1126
+
1127
+ ```ruby
1128
+ FactoryGirl.define do
1129
+ factory :user do
1130
+ initialize_with { new(name) }
1131
+
1132
+ name { 'value' }
1133
+ end
1134
+ end
1135
+
1136
+ build(:user)
1137
+ # runs
1138
+ User.new('value')
1139
+ ```
1140
+
1141
+ This prevents duplicate assignment; in versions of factory_girl before 4.0, it
1142
+ would run this:
1143
+
1144
+ ```ruby
1145
+ FactoryGirl.define do
1146
+ factory :user do
1147
+ initialize_with { new(name) }
1148
+
1149
+ name { 'value' }
1150
+ end
1151
+ end
1152
+
1153
+ build(:user)
1154
+ # runs
1155
+ user = User.new('value')
1156
+ user.name = 'value'
1157
+ ```
1158
+
1159
+ Custom Strategies
1160
+ -----------------
1161
+
1162
+ There are times where you may want to extend behavior of factory\_girl by
1163
+ adding a custom build strategy.
1164
+
1165
+ Strategies define two methods: `association` and `result`. `association`
1166
+ receives a `FactoryGirl::FactoryRunner` instance, upon which you can call
1167
+ `run`, overriding the strategy if you want. The second method, `result`,
1168
+ receives a `FactoryGirl::Evaluation` instance. It provides a way to trigger
1169
+ callbacks (with `notify`), `object` or `hash` (to get the result instance or a
1170
+ hash based on the attributes defined in the factory), and `create`, which
1171
+ executes the `to_create` callback defined on the factory.
1172
+
1173
+ To understand how factory\_girl uses strategies internally, it's probably
1174
+ easiest to just view the source for each of the four default strategies.
1175
+
1176
+ Here's an example of composing a strategy using
1177
+ `FactoryGirl::Strategy::Create` to build a JSON representation of your model.
1178
+
1179
+ ```ruby
1180
+ class JsonStrategy
1181
+ def initialize
1182
+ @strategy = FactoryGirl.strategy_by_name(:create).new
1183
+ end
1184
+
1185
+ delegate :association, to: :@strategy
1186
+
1187
+ def result(evaluation)
1188
+ @strategy.result(evaluation).to_json
1189
+ end
1190
+ end
1191
+ ```
1192
+
1193
+ For factory\_girl to recognize the new strategy, you can register it:
1194
+
1195
+ ```ruby
1196
+ FactoryGirl.register_strategy(:json, JsonStrategy)
1197
+ ```
1198
+
1199
+ This allows you to call
1200
+
1201
+ ```ruby
1202
+ FactoryGirl.json(:user)
1203
+ ```
1204
+
1205
+ Finally, you can override factory\_girl's own strategies if you'd like by
1206
+ registering a new object in place of the strategies.
1207
+
1208
+ Custom Callbacks
1209
+ ----------------
1210
+
1211
+ Custom callbacks can be defined if you're using custom strategies:
1212
+
1213
+ ```ruby
1214
+ class JsonStrategy
1215
+ def initialize
1216
+ @strategy = FactoryGirl.strategy_by_name(:create).new
1217
+ end
1218
+
1219
+ delegate :association, to: :@strategy
1220
+
1221
+ def result(evaluation)
1222
+ result = @strategy.result(evaluation)
1223
+ evaluation.notify(:before_json, result)
1224
+
1225
+ result.to_json.tap do |json|
1226
+ evaluation.notify(:after_json, json)
1227
+ evaluation.notify(:make_json_awesome, json)
1228
+ end
1229
+ end
1230
+ end
1231
+
1232
+ FactoryGirl.register_strategy(:json, JsonStrategy)
1233
+
1234
+ FactoryGirl.define do
1235
+ factory :user do
1236
+ before(:json) { |user| do_something_to(user) }
1237
+ after(:json) { |user_json| do_something_to(user_json) }
1238
+ callback(:make_json_awesome) { |user_json| do_something_to(user_json) }
1239
+ end
1240
+ end
1241
+ ```
1242
+
1243
+ Custom Methods to Persist Objects
1244
+ ---------------------------------
1245
+
1246
+ By default, creating a record will call `save!` on the instance; since this
1247
+ may not always be ideal, you can override that behavior by defining
1248
+ `to_create` on the factory:
1249
+
1250
+ ```ruby
1251
+ factory :different_orm_model do
1252
+ to_create { |instance| instance.persist! }
1253
+ end
1254
+ ```
1255
+
1256
+ To disable the persistence method altogether on create, you can `skip_create`
1257
+ for that factory:
1258
+
1259
+ ```ruby
1260
+ factory :user_without_database do
1261
+ skip_create
1262
+ end
1263
+ ```
1264
+
1265
+ To override `to_create` for all factories, define it within the
1266
+ `FactoryGirl.define` block:
1267
+
1268
+ ```ruby
1269
+ FactoryGirl.define do
1270
+ to_create { |instance| instance.persist! }
1271
+
1272
+
1273
+ factory :user do
1274
+ name "John Doe"
1275
+ end
1276
+ end
1277
+ ```
1278
+
1279
+ ActiveSupport Instrumentation
1280
+ -----------------------------
1281
+
1282
+ In order to track what factories are created (and with what build strategy),
1283
+ `ActiveSupport::Notifications` are included to provide a way to subscribe to
1284
+ factories being run. One example would be to track factories based on a
1285
+ threshold of execution time.
1286
+
1287
+ ```ruby
1288
+ ActiveSupport::Notifications.subscribe("factory_girl.run_factory") do |name, start, finish, id, payload|
1289
+ execution_time_in_seconds = finish - start
1290
+
1291
+ if execution_time_in_seconds >= 0.5
1292
+ $stderr.puts "Slow factory: #{payload[:name]} using strategy #{payload[:strategy]}"
1293
+ end
1294
+ end
1295
+ ```
1296
+
1297
+ Another example would be tracking all factories and how they're used
1298
+ throughout your test suite. If you're using RSpec, it's as simple as adding a
1299
+ `before(:suite)` and `after(:suite)`:
1300
+
1301
+ ```ruby
1302
+ factory_girl_results = {}
1303
+ config.before(:suite) do
1304
+ ActiveSupport::Notifications.subscribe("factory_girl.run_factory") do |name, start, finish, id, payload|
1305
+ factory_name = payload[:name]
1306
+ strategy_name = payload[:strategy]
1307
+ factory_girl_results[factory_name] ||= {}
1308
+ factory_girl_results[factory_name][strategy_name] ||= 0
1309
+ factory_girl_results[factory_name][strategy_name] += 1
1310
+ end
1311
+ end
1312
+
1313
+ config.after(:suite) do
1314
+ puts factory_girl_results
1315
+ end
1316
+ ```
1317
+
1318
+ Rails Preloaders and RSpec
1319
+ --------------------------
1320
+
1321
+ When running RSpec with a Rails preloader such as `spring` or `zeus`, it's possible
1322
+ to encounter an `ActiveRecord::AssociationTypeMismatch` error when creating a factory
1323
+ with associations, as below:
1324
+
1325
+ ```ruby
1326
+ FactoryGirl.define do
1327
+ factory :united_states, class: Location do
1328
+ name 'United States'
1329
+ association :location_group, factory: :north_america
1330
+ end
1331
+
1332
+ factory :north_america, class: LocationGroup do
1333
+ name 'North America'
1334
+ end
1335
+ end
1336
+ ```
1337
+
1338
+ The error occurs during the run of the test suite:
1339
+
1340
+ ```
1341
+ Failure/Error: united_states = create(:united_states)
1342
+ ActiveRecord::AssociationTypeMismatch:
1343
+ LocationGroup(#70251250797320) expected, got LocationGroup(#70251200725840)
1344
+ ```
1345
+
1346
+ The two possible solutions are to either run the suite without the preloader, or
1347
+ to add `FactoryGirl.reload` to the RSpec configuration, like so:
1348
+
1349
+ ```ruby
1350
+ RSpec.configure do |config|
1351
+ config.before(:suite) { FactoryGirl.reload }
1352
+ end
1353
+ ```
1354
+
1355
+ Using Without Bundler
1356
+ ---------------------
1357
+
1358
+ If you're not using Bundler, be sure to have the gem installed and call:
1359
+
1360
+ ```ruby
1361
+ require 'factory_girl'
1362
+ ```
1363
+
1364
+ Once required, assuming you have a directory structure of `spec/factories` or
1365
+ `test/factories`, all you'll need to do is run
1366
+
1367
+ ```ruby
1368
+ FactoryGirl.find_definitions
1369
+ ```
1370
+
1371
+ If you're using a separate directory structure for your factories, you can
1372
+ change the definition file paths before trying to find definitions:
1373
+
1374
+ ```ruby
1375
+ FactoryGirl.definition_file_paths = %w(custom_factories_directory)
1376
+ FactoryGirl.find_definitions
1377
+ ```
1378
+
1379
+ If you don't have a separate directory of factories and would like to define
1380
+ them inline, that's possible as well:
1381
+
1382
+ ```ruby
1383
+ require 'factory_girl'
1384
+
1385
+ FactoryGirl.define do
1386
+ factory :user do
1387
+ name 'John Doe'
1388
+ date_of_birth { 21.years.ago }
1389
+ end
1390
+ end
1391
+ ```