factory_bot 1.0.0.alpha

Sign up to get free protection for your applications and to get access to all the features.
Files changed (86) 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 +41 -0
  7. data/.yardopts +5 -0
  8. data/Appraisals +19 -0
  9. data/CONTRIBUTING.md +60 -0
  10. data/GETTING_STARTED.md +1387 -0
  11. data/Gemfile +8 -0
  12. data/Gemfile.lock +123 -0
  13. data/LICENSE +19 -0
  14. data/NAME.md +11 -0
  15. data/NEWS +285 -0
  16. data/README.md +102 -0
  17. data/Rakefile +36 -0
  18. data/cucumber.yml +1 -0
  19. data/factory_bot.gemspec +38 -0
  20. data/factory_girl.gemspec +41 -0
  21. data/gemfiles/3.2.gemfile +10 -0
  22. data/gemfiles/3.2.gemfile.lock +112 -0
  23. data/gemfiles/4.0.gemfile +10 -0
  24. data/gemfiles/4.0.gemfile.lock +112 -0
  25. data/gemfiles/4.1.gemfile +10 -0
  26. data/gemfiles/4.1.gemfile.lock +111 -0
  27. data/gemfiles/4.2.gemfile +10 -0
  28. data/gemfiles/4.2.gemfile.lock +111 -0
  29. data/gemfiles/5.0.gemfile +10 -0
  30. data/gemfiles/5.0.gemfile.lock +110 -0
  31. data/lib/factory_bot.rb +154 -0
  32. data/lib/factory_bot/aliases.rb +18 -0
  33. data/lib/factory_bot/attribute.rb +62 -0
  34. data/lib/factory_bot/attribute/association.rb +27 -0
  35. data/lib/factory_bot/attribute/dynamic.rb +24 -0
  36. data/lib/factory_bot/attribute/sequence.rb +16 -0
  37. data/lib/factory_bot/attribute/static.rb +16 -0
  38. data/lib/factory_bot/attribute_assigner.rb +97 -0
  39. data/lib/factory_bot/attribute_list.rb +67 -0
  40. data/lib/factory_bot/callback.rb +40 -0
  41. data/lib/factory_bot/callbacks_observer.rb +21 -0
  42. data/lib/factory_bot/configuration.rb +37 -0
  43. data/lib/factory_bot/declaration.rb +23 -0
  44. data/lib/factory_bot/declaration/association.rb +28 -0
  45. data/lib/factory_bot/declaration/dynamic.rb +26 -0
  46. data/lib/factory_bot/declaration/implicit.rb +33 -0
  47. data/lib/factory_bot/declaration/static.rb +26 -0
  48. data/lib/factory_bot/declaration_list.rb +49 -0
  49. data/lib/factory_bot/decorator.rb +21 -0
  50. data/lib/factory_bot/decorator/attribute_hash.rb +16 -0
  51. data/lib/factory_bot/decorator/class_key_hash.rb +28 -0
  52. data/lib/factory_bot/decorator/disallows_duplicates_registry.rb +13 -0
  53. data/lib/factory_bot/decorator/invocation_tracker.rb +19 -0
  54. data/lib/factory_bot/decorator/new_constructor.rb +12 -0
  55. data/lib/factory_bot/definition.rb +136 -0
  56. data/lib/factory_bot/definition_hierarchy.rb +48 -0
  57. data/lib/factory_bot/definition_proxy.rb +174 -0
  58. data/lib/factory_bot/errors.rb +25 -0
  59. data/lib/factory_bot/evaluation.rb +23 -0
  60. data/lib/factory_bot/evaluator.rb +82 -0
  61. data/lib/factory_bot/evaluator_class_definer.rb +20 -0
  62. data/lib/factory_bot/factory.rb +162 -0
  63. data/lib/factory_bot/factory_runner.rb +33 -0
  64. data/lib/factory_bot/find_definitions.rb +25 -0
  65. data/lib/factory_bot/linter.rb +97 -0
  66. data/lib/factory_bot/null_factory.rb +18 -0
  67. data/lib/factory_bot/null_object.rb +24 -0
  68. data/lib/factory_bot/registry.rb +38 -0
  69. data/lib/factory_bot/reload.rb +8 -0
  70. data/lib/factory_bot/sequence.rb +62 -0
  71. data/lib/factory_bot/strategy/attributes_for.rb +13 -0
  72. data/lib/factory_bot/strategy/build.rb +15 -0
  73. data/lib/factory_bot/strategy/create.rb +18 -0
  74. data/lib/factory_bot/strategy/null.rb +11 -0
  75. data/lib/factory_bot/strategy/stub.rb +108 -0
  76. data/lib/factory_bot/strategy_calculator.rb +26 -0
  77. data/lib/factory_bot/strategy_syntax_method_registrar.rb +54 -0
  78. data/lib/factory_bot/syntax.rb +7 -0
  79. data/lib/factory_bot/syntax/default.rb +76 -0
  80. data/lib/factory_bot/syntax/methods.rb +111 -0
  81. data/lib/factory_bot/syntax_runner.rb +6 -0
  82. data/lib/factory_bot/trait.rb +30 -0
  83. data/lib/factory_bot/version.rb +3 -0
  84. data/lib/factory_girl.rb +5 -0
  85. data/lib/factory_girl/version.rb +1 -0
  86. metadata +302 -0
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: fcff4a8af6eb5f509ff19dd5a333ec6c3de2e8cd
4
+ data.tar.gz: e9d8214553953b1c61148eccfa7f7b810e7e045d
5
+ SHA512:
6
+ metadata.gz: 682388106908e80999ded8c4ccce299dd3f2260ecf263ea11c69e48197a6a8f1403c45cabbc5f4fc7fc4712c330538de2c58e554b65bd26effd0ee383937a261
7
+ data.tar.gz: 0c6d58ea99fcd57e988f375a750403020717455bdcd6d382e7f13333e82f4eae48d2bf1a99ffcdcef4d61e9f4d66cdac2dbc8af9c90235fc231eb6b0ec1fd1ec
data/.autotest ADDED
@@ -0,0 +1,9 @@
1
+ Autotest.add_hook :initialize do |at|
2
+ at.clear_mappings
3
+
4
+ at.add_mapping(%r{^test/.*_test\.rb$}) {|f, _| [f] }
5
+ at.add_mapping(%r{^lib/factory_girl/(.*)\.rb$}) {|_, m| ["test/#{m[1]}_test.rb",
6
+ "test/integration_test.rb"] }
7
+ at.add_mapping(%r{^test/(test_helper|models)\.rb$}) { at.files_matching %r{^test/.*_test\.rb$} }
8
+ at.add_mapping(%r{^lib/.*\.rb$}) { at.files_matching %r{^test/.*_test\.rb$} }
9
+ end
data/.gitignore ADDED
@@ -0,0 +1,9 @@
1
+ *.swp
2
+ test.db
3
+ factory_girl-*.gem
4
+ doc
5
+ .yardoc
6
+ coverage
7
+ .bundle
8
+ tmp
9
+ bin
data/.rspec ADDED
@@ -0,0 +1,2 @@
1
+ --format progress
2
+ --color
data/.simplecov ADDED
@@ -0,0 +1,4 @@
1
+ SimpleCov.start do
2
+ add_filter "/spec/"
3
+ add_filter "/tmp/"
4
+ end
data/.travis.yml ADDED
@@ -0,0 +1,41 @@
1
+ rvm:
2
+ - 1.9.3
3
+ - 2.0.0
4
+ - 2.1.9
5
+ - 2.2.5
6
+ - 2.3.1
7
+ - ruby-head
8
+ - jruby-19mode
9
+ - rbx-2
10
+ before_install:
11
+ - gem update --system
12
+ - gem update bundler
13
+ - gem cleanup bundler
14
+ install: "bundle install --jobs 8"
15
+ script: "bundle exec rake"
16
+ gemfile:
17
+ - gemfiles/3.2.gemfile
18
+ - gemfiles/4.0.gemfile
19
+ - gemfiles/4.1.gemfile
20
+ - gemfiles/4.2.gemfile
21
+ - gemfiles/5.0.gemfile
22
+ matrix:
23
+ fast_finish: true
24
+ exclude:
25
+ - rvm: 1.9.3
26
+ gemfile: gemfiles/5.0.gemfile
27
+ - rvm: 2.0.0
28
+ gemfile: gemfiles/5.0.gemfile
29
+ - rvm: 2.1.9
30
+ gemfile: gemfiles/5.0.gemfile
31
+ allow_failures:
32
+ - rvm: ruby-head
33
+ - rvm: jruby-19mode
34
+ gemfile: gemfiles/5.0.gemfile
35
+ - rvm: rbx-2
36
+ branches:
37
+ only:
38
+ - master
39
+
40
+ sudo: false
41
+ cache: bundler
data/.yardopts ADDED
@@ -0,0 +1,5 @@
1
+ lib/**/*.rb
2
+ -
3
+ GETTING_STARTED.md
4
+ CONTRIBUTING.md
5
+ LICENSE
data/Appraisals ADDED
@@ -0,0 +1,19 @@
1
+ appraise "3.2" do
2
+ gem "activerecord", git: 'https://github.com/rails/rails.git', branch: '3-2-stable'
3
+ end
4
+
5
+ appraise '4.0' do
6
+ gem 'activerecord', "~> 4.0.13"
7
+ end
8
+
9
+ appraise '4.1' do
10
+ gem 'activerecord', "~> 4.1.14"
11
+ end
12
+
13
+ appraise '4.2' do
14
+ gem 'activerecord', "~> 4.2.5.1"
15
+ end
16
+
17
+ appraise '5.0' do
18
+ gem 'activerecord', "~> 5.0.0"
19
+ end
data/CONTRIBUTING.md ADDED
@@ -0,0 +1,60 @@
1
+ # Contributing to Factory Bot
2
+
3
+ We love pull requests from everyone. By participating in this project, you
4
+ agree to abide by the thoughtbot [code of conduct].
5
+
6
+ [code of conduct]: https://thoughtbot.com/open-source-code-of-conduct
7
+
8
+ Here are some ways *you* can contribute:
9
+
10
+ * by using alpha, beta, and prerelease versions
11
+ * by reporting bugs
12
+ * by suggesting new features
13
+ * by writing or editing documentation
14
+ * by writing specifications
15
+ * by writing code ( **no patch is too small** : fix typos, add comments, clean up inconsistent whitespace )
16
+ * by refactoring code
17
+ * by closing [issues][]
18
+ * by reviewing patches
19
+
20
+ [issues]: https://github.com/thoughtbot/factory_bot/issues
21
+
22
+ ## Submitting an Issue
23
+
24
+ * We use the [GitHub issue tracker][issues] to track bugs and features.
25
+ * Before submitting a bug report or feature request, check to make sure it hasn't
26
+ already been submitted.
27
+ * When submitting a bug report, please include a [Gist][] that includes a stack
28
+ trace and any details that may be necessary to reproduce the bug, including
29
+ your gem version, Ruby version, and operating system. Ideally, a bug report
30
+ should include a pull request with failing specs.
31
+
32
+ [gist]: https://gist.github.com/
33
+
34
+ ## Cleaning up issues
35
+
36
+ * Issues that have no response from the submitter will be closed after 30 days.
37
+ * Issues will be closed once they're assumed to be fixed or answered. If the
38
+ maintainer is wrong, it can be opened again.
39
+ * If your issue is closed by mistake, please understand and explain the issue.
40
+ We will happily reopen the issue.
41
+
42
+ ## Submitting a Pull Request
43
+ 1. [Fork][fork] the [official repository][repo].
44
+ 2. [Create a topic branch.][branch]
45
+ 3. Implement your feature or bug fix.
46
+ 4. Add, commit, and push your changes.
47
+ 5. [Submit a pull request.][pr]
48
+
49
+ ## Notes
50
+ * Please add tests if you changed code. Contributions without tests won't be accepted.
51
+ * If you don't know how to add tests, please put in a PR and leave a comment
52
+ asking for help. We love helping!
53
+ * Please don't update the Gem version.
54
+
55
+ [repo]: https://github.com/thoughtbot/factory_bot/tree/master
56
+ [fork]: https://help.github.com/articles/fork-a-repo/
57
+ [branch]: https://help.github.com/articles/creating-and-deleting-branches-within-your-repository/
58
+ [pr]: https://help.github.com/articles/using-pull-requests/
59
+
60
+ Inspired by https://github.com/middleman/middleman-heroku/blob/master/CONTRIBUTING.md
@@ -0,0 +1,1387 @@
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_bot_rails`:
8
+
9
+ ```ruby
10
+ gem "factory_bot_rails", "~> 4.0"
11
+ ```
12
+
13
+ If you're *not* using Rails, you'll just have to change the required version of `factory_bot`:
14
+
15
+ ```ruby
16
+ gem "factory_bot", "~> 4.0"
17
+ ```
18
+
19
+ JRuby users: factory_bot 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_bot.rb
35
+ RSpec.configure do |config|
36
+ config.include FactoryBot::Syntax::Methods
37
+ end
38
+
39
+ # RSpec without Rails
40
+ RSpec.configure do |config|
41
+ config.include FactoryBot::Syntax::Methods
42
+
43
+ config.before(:suite) do
44
+ FactoryBot.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_bot'
53
+ ```
54
+
55
+ # Test::Unit
56
+
57
+ ```ruby
58
+ class Test::Unit::TestCase
59
+ include FactoryBot::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(FactoryBot::Syntax::Methods)
68
+ ```
69
+
70
+ # Spinach
71
+
72
+ ```ruby
73
+ class Spinach::FeatureSteps
74
+ include FactoryBot::Syntax::Methods
75
+ end
76
+ ```
77
+
78
+ # Minitest
79
+
80
+ ```ruby
81
+ class Minitest::Unit::TestCase
82
+ include FactoryBot::Syntax::Methods
83
+ end
84
+ ```
85
+
86
+ # Minitest::Spec
87
+
88
+ ```ruby
89
+ class Minitest::Spec
90
+ include FactoryBot::Syntax::Methods
91
+ end
92
+ ```
93
+
94
+ # minitest-rails
95
+
96
+ ```ruby
97
+ class ActiveSupport::TestCase
98
+ include FactoryBot::Syntax::Methods
99
+ end
100
+ ```
101
+
102
+ If you do not include `FactoryBot::Syntax::Methods` in your test suite, then all factory_bot methods will need to be prefaced with `FactoryBot`.
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
+ FactoryBot.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 `FactoryBot.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\_bot 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_bot 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_bot 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_bot's dynamic attributes, you can access transient attributes as
272
+ you would expect. If you need to access the evaluator in a factory_bot 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
+ FactoryBot.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
+ FactoryBot.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
+ FactoryBot.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_bot.
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\_bot makes available four callbacks for injecting some code:
789
+
790
+ * after(:build) - called after a factory is built (via `FactoryBot.build`, `FactoryBot.create`)
791
+ * before(:create) - called before a factory is saved (via `FactoryBot.create`)
792
+ * after(:create) - called after a factory is saved (via `FactoryBot.create`)
793
+ * after(:stub) - called after a factory is stubbed (via `FactoryBot.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
+ `FactoryBot.define` block:
840
+
841
+ ```ruby
842
+ FactoryBot.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
+ FactoryBot.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
+ FactoryBot.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
+ FactoryBot.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
+ FactoryBot.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
+ `FactoryBot.modify` must be called outside of a `FactoryBot.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_bot allows for linting known factories:
963
+
964
+ ```ruby
965
+ FactoryBot.lint
966
+ ```
967
+
968
+ `FactoryBot.lint` creates each factory and catches any exceptions raised
969
+ during the creation process. `FactoryBot::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 `FactoryBot.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_bot.rake
985
+ namespace :factory_bot do
986
+ desc "Verify that all FactoryBot factories are valid"
987
+ task lint: :environment do
988
+ if Rails.env.test?
989
+ begin
990
+ DatabaseCleaner.start
991
+ FactoryBot.lint
992
+ ensure
993
+ DatabaseCleaner.clean
994
+ end
995
+ else
996
+ system("bundle exec rake factory_bot:lint RAILS_ENV='test'")
997
+ end
998
+ end
999
+ end
1000
+ ```
1001
+
1002
+ After calling `FactoryBot.lint`, you'll likely want to clear out the
1003
+ database, as records will most likely be created. The provided example above
1004
+ uses the database_cleaner gem to clear out the database; be sure to add the
1005
+ gem to your Gemfile under the appropriate groups.
1006
+
1007
+ You can lint factories selectively by passing only factories you want linted:
1008
+
1009
+ ```ruby
1010
+ factories_to_lint = FactoryBot.factories.reject do |factory|
1011
+ factory.name =~ /^old_/
1012
+ end
1013
+
1014
+ FactoryBot.lint factories_to_lint
1015
+ ```
1016
+
1017
+ This would lint all factories that aren't prefixed with `old_`.
1018
+
1019
+ Traits can also be linted. This option verifies that each
1020
+ and every trait of a factory generates a valid object on its own.
1021
+ This is turned on by passing `traits: true` to the `lint` method:
1022
+
1023
+ ```ruby
1024
+ FactoryBot.lint traits: true
1025
+ ```
1026
+
1027
+ This can also be combined with other arguments:
1028
+
1029
+ ```ruby
1030
+ FactoryBot.lint factories_to_lint, traits: true
1031
+ ```
1032
+
1033
+ Custom Construction
1034
+ -------------------
1035
+
1036
+ If you want to use factory_bot to construct an object where some attributes
1037
+ are passed to `initialize` or if you want to do something other than simply
1038
+ calling `new` on your build class, you can override the default behavior by
1039
+ defining `initialize_with` on your factory. Example:
1040
+
1041
+ ```ruby
1042
+ # user.rb
1043
+ class User
1044
+ attr_accessor :name, :email
1045
+
1046
+ def initialize(name)
1047
+ @name = name
1048
+ end
1049
+ end
1050
+
1051
+ # factories.rb
1052
+ sequence(:email) { |n| "person#{n}@example.com" }
1053
+
1054
+ factory :user do
1055
+ name "Jane Doe"
1056
+ email
1057
+
1058
+ initialize_with { new(name) }
1059
+ end
1060
+
1061
+ build(:user).name # Jane Doe
1062
+ ```
1063
+
1064
+ Although factory_bot is written to work with ActiveRecord out of the box, it
1065
+ can also work with any Ruby class. For maximum compatibility with ActiveRecord,
1066
+ the default initializer builds all instances by calling `new` on your build class
1067
+ without any arguments. It then calls attribute writer methods to assign all the
1068
+ attribute values. While that works fine for ActiveRecord, it actually doesn't
1069
+ work for almost any other Ruby class.
1070
+
1071
+ You can override the initializer in order to:
1072
+
1073
+ * Build non-ActiveRecord objects that require arguments to `initialize`
1074
+ * Use a method other than `new` to instantiate the instance
1075
+ * Do crazy things like decorate the instance after it's built
1076
+
1077
+ When using `initialize_with`, you don't have to declare the class itself when
1078
+ calling `new`; however, any other class methods you want to call will have to
1079
+ be called on the class explicitly.
1080
+
1081
+ For example:
1082
+
1083
+ ```ruby
1084
+ factory :user do
1085
+ name "John Doe"
1086
+
1087
+ initialize_with { User.build_with_name(name) }
1088
+ end
1089
+ ```
1090
+
1091
+ You can also access all public attributes within the `initialize_with` block
1092
+ by calling `attributes`:
1093
+
1094
+ ```ruby
1095
+ factory :user do
1096
+ transient do
1097
+ comments_count 5
1098
+ end
1099
+
1100
+ name "John Doe"
1101
+
1102
+ initialize_with { new(attributes) }
1103
+ end
1104
+ ```
1105
+
1106
+ This will build a hash of all attributes to be passed to `new`. It won't
1107
+ include transient attributes, but everything else defined in the factory will be
1108
+ passed (associations, evalued sequences, etc.)
1109
+
1110
+ You can define `initialize_with` for all factories by including it in the
1111
+ `FactoryBot.define` block:
1112
+
1113
+ ```ruby
1114
+ FactoryBot.define do
1115
+ initialize_with { new("Awesome first argument") }
1116
+ end
1117
+ ```
1118
+
1119
+ When using `initialize_with`, attributes accessed from within the `initialize_with`
1120
+ block are assigned *only* in the constructor; this equates to roughly the
1121
+ following code:
1122
+
1123
+ ```ruby
1124
+ FactoryBot.define do
1125
+ factory :user do
1126
+ initialize_with { new(name) }
1127
+
1128
+ name { 'value' }
1129
+ end
1130
+ end
1131
+
1132
+ build(:user)
1133
+ # runs
1134
+ User.new('value')
1135
+ ```
1136
+
1137
+ This prevents duplicate assignment; in versions of factory_bot before 4.0, it
1138
+ would run this:
1139
+
1140
+ ```ruby
1141
+ FactoryBot.define do
1142
+ factory :user do
1143
+ initialize_with { new(name) }
1144
+
1145
+ name { 'value' }
1146
+ end
1147
+ end
1148
+
1149
+ build(:user)
1150
+ # runs
1151
+ user = User.new('value')
1152
+ user.name = 'value'
1153
+ ```
1154
+
1155
+ Custom Strategies
1156
+ -----------------
1157
+
1158
+ There are times where you may want to extend behavior of factory\_bot by
1159
+ adding a custom build strategy.
1160
+
1161
+ Strategies define two methods: `association` and `result`. `association`
1162
+ receives a `FactoryBot::FactoryRunner` instance, upon which you can call
1163
+ `run`, overriding the strategy if you want. The second method, `result`,
1164
+ receives a `FactoryBot::Evaluation` instance. It provides a way to trigger
1165
+ callbacks (with `notify`), `object` or `hash` (to get the result instance or a
1166
+ hash based on the attributes defined in the factory), and `create`, which
1167
+ executes the `to_create` callback defined on the factory.
1168
+
1169
+ To understand how factory\_bot uses strategies internally, it's probably
1170
+ easiest to just view the source for each of the four default strategies.
1171
+
1172
+ Here's an example of composing a strategy using
1173
+ `FactoryBot::Strategy::Create` to build a JSON representation of your model.
1174
+
1175
+ ```ruby
1176
+ class JsonStrategy
1177
+ def initialize
1178
+ @strategy = FactoryBot.strategy_by_name(:create).new
1179
+ end
1180
+
1181
+ delegate :association, to: :@strategy
1182
+
1183
+ def result(evaluation)
1184
+ @strategy.result(evaluation).to_json
1185
+ end
1186
+ end
1187
+ ```
1188
+
1189
+ For factory\_bot to recognize the new strategy, you can register it:
1190
+
1191
+ ```ruby
1192
+ FactoryBot.register_strategy(:json, JsonStrategy)
1193
+ ```
1194
+
1195
+ This allows you to call
1196
+
1197
+ ```ruby
1198
+ FactoryBot.json(:user)
1199
+ ```
1200
+
1201
+ Finally, you can override factory\_bot's own strategies if you'd like by
1202
+ registering a new object in place of the strategies.
1203
+
1204
+ Custom Callbacks
1205
+ ----------------
1206
+
1207
+ Custom callbacks can be defined if you're using custom strategies:
1208
+
1209
+ ```ruby
1210
+ class JsonStrategy
1211
+ def initialize
1212
+ @strategy = FactoryBot.strategy_by_name(:create).new
1213
+ end
1214
+
1215
+ delegate :association, to: :@strategy
1216
+
1217
+ def result(evaluation)
1218
+ result = @strategy.result(evaluation)
1219
+ evaluation.notify(:before_json, result)
1220
+
1221
+ result.to_json.tap do |json|
1222
+ evaluation.notify(:after_json, json)
1223
+ evaluation.notify(:make_json_awesome, json)
1224
+ end
1225
+ end
1226
+ end
1227
+
1228
+ FactoryBot.register_strategy(:json, JsonStrategy)
1229
+
1230
+ FactoryBot.define do
1231
+ factory :user do
1232
+ before(:json) { |user| do_something_to(user) }
1233
+ after(:json) { |user_json| do_something_to(user_json) }
1234
+ callback(:make_json_awesome) { |user_json| do_something_to(user_json) }
1235
+ end
1236
+ end
1237
+ ```
1238
+
1239
+ Custom Methods to Persist Objects
1240
+ ---------------------------------
1241
+
1242
+ By default, creating a record will call `save!` on the instance; since this
1243
+ may not always be ideal, you can override that behavior by defining
1244
+ `to_create` on the factory:
1245
+
1246
+ ```ruby
1247
+ factory :different_orm_model do
1248
+ to_create { |instance| instance.persist! }
1249
+ end
1250
+ ```
1251
+
1252
+ To disable the persistence method altogether on create, you can `skip_create`
1253
+ for that factory:
1254
+
1255
+ ```ruby
1256
+ factory :user_without_database do
1257
+ skip_create
1258
+ end
1259
+ ```
1260
+
1261
+ To override `to_create` for all factories, define it within the
1262
+ `FactoryBot.define` block:
1263
+
1264
+ ```ruby
1265
+ FactoryBot.define do
1266
+ to_create { |instance| instance.persist! }
1267
+
1268
+
1269
+ factory :user do
1270
+ name "John Doe"
1271
+ end
1272
+ end
1273
+ ```
1274
+
1275
+ ActiveSupport Instrumentation
1276
+ -----------------------------
1277
+
1278
+ In order to track what factories are created (and with what build strategy),
1279
+ `ActiveSupport::Notifications` are included to provide a way to subscribe to
1280
+ factories being run. One example would be to track factories based on a
1281
+ threshold of execution time.
1282
+
1283
+ ```ruby
1284
+ ActiveSupport::Notifications.subscribe("factory_bot.run_factory") do |name, start, finish, id, payload|
1285
+ execution_time_in_seconds = finish - start
1286
+
1287
+ if execution_time_in_seconds >= 0.5
1288
+ $stderr.puts "Slow factory: #{payload[:name]} using strategy #{payload[:strategy]}"
1289
+ end
1290
+ end
1291
+ ```
1292
+
1293
+ Another example would be tracking all factories and how they're used
1294
+ throughout your test suite. If you're using RSpec, it's as simple as adding a
1295
+ `before(:suite)` and `after(:suite)`:
1296
+
1297
+ ```ruby
1298
+ factory_bot_results = {}
1299
+ config.before(:suite) do
1300
+ ActiveSupport::Notifications.subscribe("factory_bot.run_factory") do |name, start, finish, id, payload|
1301
+ factory_name = payload[:name]
1302
+ strategy_name = payload[:strategy]
1303
+ factory_bot_results[factory_name] ||= {}
1304
+ factory_bot_results[factory_name][strategy_name] ||= 0
1305
+ factory_bot_results[factory_name][strategy_name] += 1
1306
+ end
1307
+ end
1308
+
1309
+ config.after(:suite) do
1310
+ puts factory_bot_results
1311
+ end
1312
+ ```
1313
+
1314
+ Rails Preloaders and RSpec
1315
+ --------------------------
1316
+
1317
+ When running RSpec with a Rails preloader such as `spring` or `zeus`, it's possible
1318
+ to encounter an `ActiveRecord::AssociationTypeMismatch` error when creating a factory
1319
+ with associations, as below:
1320
+
1321
+ ```ruby
1322
+ FactoryBot.define do
1323
+ factory :united_states, class: Location do
1324
+ name 'United States'
1325
+ association :location_group, factory: :north_america
1326
+ end
1327
+
1328
+ factory :north_america, class: LocationGroup do
1329
+ name 'North America'
1330
+ end
1331
+ end
1332
+ ```
1333
+
1334
+ The error occurs during the run of the test suite:
1335
+
1336
+ ```
1337
+ Failure/Error: united_states = create(:united_states)
1338
+ ActiveRecord::AssociationTypeMismatch:
1339
+ LocationGroup(#70251250797320) expected, got LocationGroup(#70251200725840)
1340
+ ```
1341
+
1342
+ The two possible solutions are to either run the suite without the preloader, or
1343
+ to add `FactoryBot.reload` to the RSpec configuration, like so:
1344
+
1345
+ ```ruby
1346
+ RSpec.configure do |config|
1347
+ config.before(:suite) { FactoryBot.reload }
1348
+ end
1349
+ ```
1350
+
1351
+ Using Without Bundler
1352
+ ---------------------
1353
+
1354
+ If you're not using Bundler, be sure to have the gem installed and call:
1355
+
1356
+ ```ruby
1357
+ require 'factory_bot'
1358
+ ```
1359
+
1360
+ Once required, assuming you have a directory structure of `spec/factories` or
1361
+ `test/factories`, all you'll need to do is run
1362
+
1363
+ ```ruby
1364
+ FactoryBot.find_definitions
1365
+ ```
1366
+
1367
+ If you're using a separate directory structure for your factories, you can
1368
+ change the definition file paths before trying to find definitions:
1369
+
1370
+ ```ruby
1371
+ FactoryBot.definition_file_paths = %w(custom_factories_directory)
1372
+ FactoryBot.find_definitions
1373
+ ```
1374
+
1375
+ If you don't have a separate directory of factories and would like to define
1376
+ them inline, that's possible as well:
1377
+
1378
+ ```ruby
1379
+ require 'factory_bot'
1380
+
1381
+ FactoryBot.define do
1382
+ factory :user do
1383
+ name 'John Doe'
1384
+ date_of_birth { 21.years.ago }
1385
+ end
1386
+ end
1387
+ ```