2011-02-07 22:48:29 +00:00
Getting Started
===============
2011-07-04 13:49:09 +00:00
Update Your Gemfile
-------------------
2018-09-18 01:43:01 +00:00
If you're using Rails:
2011-07-04 13:49:09 +00:00
2012-01-13 16:44:27 +00:00
```ruby
2018-09-18 01:43:01 +00:00
gem "factory_bot_rails"
2012-01-13 16:44:27 +00:00
```
2011-07-04 13:49:09 +00:00
2018-09-18 01:43:01 +00:00
If you're *not* using Rails:
2011-07-04 13:49:09 +00:00
2012-01-13 16:44:27 +00:00
```ruby
2018-09-18 01:43:01 +00:00
gem "factory_bot"
2012-01-13 16:44:27 +00:00
```
2011-07-04 13:49:09 +00:00
2017-10-20 19:20:28 +00:00
JRuby users: factory_bot works with JRuby starting with 1.6.7.2 (latest stable, as per July 2012).
2012-07-06 09:27:40 +00:00
JRuby has to be used in 1.9 mode, for that, use JRUBY_OPTS environment variable:
2013-09-04 16:29:47 +00:00
```bash
2012-07-06 09:27:40 +00:00
export JRUBY_OPTS=--1.9
```
2011-07-04 13:49:09 +00:00
Once your Gemfile is updated, you'll want to update your bundle.
2013-12-13 15:02:23 +00:00
Configure your test suite
-------------------------
2012-06-19 12:06:16 +00:00
2018-02-01 14:36:22 +00:00
### RSpec
2016-12-16 10:16:25 +00:00
2019-03-24 16:46:09 +00:00
If you're using Rails, add the following configuration to `spec/support/factory_bot.rb` and be sure to require that file in `rails_helper.rb` :
2018-06-11 21:41:34 +00:00
2016-12-16 10:16:25 +00:00
```ruby
2013-12-13 15:02:23 +00:00
RSpec.configure do |config|
2017-10-20 19:20:28 +00:00
config.include FactoryBot::Syntax::Methods
2013-12-13 15:02:23 +00:00
end
2018-06-11 21:41:34 +00:00
```
2012-06-19 12:06:16 +00:00
2018-06-11 21:41:34 +00:00
If you're *not* using Rails:
```ruby
2015-11-22 10:46:26 +00:00
RSpec.configure do |config|
2017-10-20 19:20:28 +00:00
config.include FactoryBot::Syntax::Methods
2015-11-22 10:46:26 +00:00
config.before(:suite) do
2017-10-20 19:20:28 +00:00
FactoryBot.find_definitions
2015-11-22 10:46:26 +00:00
end
end
2016-04-08 12:15:17 +00:00
```
2015-11-22 10:46:26 +00:00
2018-02-01 14:36:22 +00:00
### Test::Unit
2016-04-05 18:15:58 +00:00
```ruby
2013-12-13 15:02:23 +00:00
class Test::Unit::TestCase
2017-10-20 19:20:28 +00:00
include FactoryBot::Syntax::Methods
2013-12-13 15:02:23 +00:00
end
2016-04-05 18:15:58 +00:00
```
2012-06-19 12:06:16 +00:00
2018-02-01 14:36:22 +00:00
### Cucumber
2016-04-05 18:15:58 +00:00
```ruby
2015-12-08 21:09:16 +00:00
# env.rb (Rails example location - RAILS_ROOT/features/support/env.rb)
2017-10-20 19:20:28 +00:00
World(FactoryBot::Syntax::Methods)
2016-04-05 18:15:58 +00:00
```
2012-06-19 12:06:16 +00:00
2018-02-01 14:36:22 +00:00
### Spinach
2016-04-05 18:15:58 +00:00
```ruby
2014-02-05 11:09:29 +00:00
class Spinach::FeatureSteps
2017-10-20 19:20:28 +00:00
include FactoryBot::Syntax::Methods
2014-02-05 11:09:29 +00:00
end
2016-04-05 18:15:58 +00:00
```
2014-02-05 11:09:29 +00:00
2018-02-01 14:36:22 +00:00
### Minitest
2016-04-05 18:15:58 +00:00
```ruby
2015-05-09 13:42:26 +00:00
class Minitest::Unit::TestCase
2017-10-20 19:20:28 +00:00
include FactoryBot::Syntax::Methods
2013-12-13 15:02:23 +00:00
end
2016-04-05 18:15:58 +00:00
```
2012-06-19 12:06:16 +00:00
2018-02-01 14:36:22 +00:00
### Minitest::Spec
2016-04-05 18:15:58 +00:00
```ruby
2015-05-09 13:42:26 +00:00
class Minitest::Spec
2017-10-20 19:20:28 +00:00
include FactoryBot::Syntax::Methods
2013-12-13 15:02:23 +00:00
end
2016-04-05 18:15:58 +00:00
```
2012-06-19 12:06:16 +00:00
2018-02-01 14:36:22 +00:00
### minitest-rails
2016-04-05 18:15:58 +00:00
```ruby
2015-10-20 16:42:45 +00:00
class ActiveSupport::TestCase
2017-10-20 19:20:28 +00:00
include FactoryBot::Syntax::Methods
2012-06-19 12:06:16 +00:00
end
```
2017-10-20 19:20:28 +00:00
If you do not include `FactoryBot::Syntax::Methods` in your test suite, then all factory_bot methods will need to be prefaced with `FactoryBot` .
2013-12-13 15:02:23 +00:00
2011-02-07 22:48:29 +00:00
Defining factories
------------------
2018-10-21 23:33:20 +00:00
Each factory has a name and a set of attributes. The name is used to guess the class of the object by default:
2011-02-07 22:48:29 +00:00
2012-01-13 16:44:27 +00:00
```ruby
# This will guess the User class
2017-10-20 19:20:28 +00:00
FactoryBot.define do
2012-01-13 16:44:27 +00:00
factory :user do
2018-08-15 18:19:11 +00:00
first_name { "John" }
last_name { "Doe" }
admin { false }
2012-01-13 16:44:27 +00:00
end
end
```
2011-02-07 22:48:29 +00:00
2018-10-21 23:33:20 +00:00
It is also possible to explicitly specify the class:
```ruby
# This will use the User class (otherwise Admin would have been guessed)
2019-12-18 23:58:58 +00:00
factory :admin, class: "User"
2018-10-21 23:33:20 +00:00
```
If the constant is not available
(if you are using a Rails engine that waits to load models, for example),
you can also pass a symbol or string,
which factory_bot will constantize later, once you start building objects:
```ruby
# It's OK if Doorkeeper::AccessToken isn't loaded yet
factory :access_token, class: "Doorkeeper::AccessToken"
```
2018-08-15 18:19:11 +00:00
Because of the block syntax in Ruby, defining attributes as `Hash` es (for
serialized/JSON columns, for example) requires two sets of curly brackets:
```ruby
factory :program do
configuration { { auto_resolve: false, auto_define: true } }
end
```
2011-02-07 22:48:29 +00:00
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.
Attempting to define multiple factories with the same name will raise an error.
2015-11-22 10:46:26 +00:00
Factories can be defined anywhere, but will be automatically loaded after
2017-10-20 19:20:28 +00:00
calling `FactoryBot.find_definitions` if factories are defined in files at the
2015-11-22 10:46:26 +00:00
following locations:
2011-02-07 22:48:29 +00:00
test/factories.rb
spec/factories.rb
test/factories/*.rb
spec/factories/*.rb
Using factories
---------------
2017-10-20 19:20:28 +00:00
factory\_bot supports several different build strategies: build, create, attributes\_for and build\_stubbed:
2011-02-07 22:48:29 +00:00
2012-01-13 16:44:27 +00:00
```ruby
# Returns a User instance that's not saved
2013-12-13 15:02:23 +00:00
user = build(:user)
2011-06-29 15:46:59 +00:00
2012-01-13 16:44:27 +00:00
# Returns a saved User instance
2013-12-13 15:02:23 +00:00
user = create(:user)
2011-06-29 15:46:59 +00:00
2012-01-13 16:44:27 +00:00
# Returns a hash of attributes that can be used to build a User instance
2013-12-13 15:02:23 +00:00
attrs = attributes_for(:user)
2011-06-29 15:46:59 +00:00
2012-01-13 16:44:27 +00:00
# Returns an object with all defined attributes stubbed out
2013-12-13 15:02:23 +00:00
stub = build_stubbed(:user)
2011-10-12 15:35:10 +00:00
2012-01-13 16:44:27 +00:00
# Passing a block to any of the methods above will yield the return object
2013-12-13 15:02:23 +00:00
create(:user) do |user|
2012-01-13 16:44:27 +00:00
user.posts.create(attributes_for(:post))
end
```
2011-02-07 22:48:29 +00:00
No matter which strategy is used, it's possible to override the defined attributes by passing a hash:
2012-01-13 16:44:27 +00:00
```ruby
# Build a User instance and override the first_name property
2013-12-13 15:02:23 +00:00
user = build(:user, first_name: "Joe")
2012-01-13 16:44:27 +00:00
user.first_name
# => "Joe"
```
2011-02-07 22:48:29 +00:00
2018-10-28 01:39:14 +00:00
Note that objects created with `build_stubbed` cannot be serialized with
`Marshal.dump` , since factory_bot defines singleton methods on these objects.
2018-08-15 18:19:11 +00:00
Static Attributes
2016-02-09 02:34:05 +00:00
------------------
2011-02-07 22:48:29 +00:00
2018-09-14 19:02:33 +00:00
Static attributes (without a block) are no longer available in factory\_bot 5.
You can read more about the decision to remove them in
[this blog post ](https://robots.thoughtbot.com/deprecating-static-attributes-in-factory_bot-4-11 ).
2016-02-06 03:11:25 +00:00
2011-07-01 15:14:27 +00:00
Aliases
-------
2018-06-12 19:49:36 +00:00
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 an author factory in vain. So, alias your user factory so it can be used under alias names.
2011-07-01 15:14:27 +00:00
2012-01-13 16:44:27 +00:00
```ruby
2012-03-31 15:36:20 +00:00
factory :user, aliases: [:author, :commenter] do
2018-08-15 18:19:11 +00:00
first_name { "John" }
last_name { "Doe" }
2012-01-13 16:44:27 +00:00
date_of_birth { 18.years.ago }
end
factory :post do
author
# instead of
2012-03-31 15:36:20 +00:00
# association :author, factory: :user
2018-08-15 18:19:11 +00:00
title { "How to read a book effectively" }
body { "There are five steps involved." }
2012-01-13 16:44:27 +00:00
end
factory :comment do
commenter
# instead of
2012-03-31 15:36:20 +00:00
# association :commenter, factory: :user
2018-08-15 18:19:11 +00:00
body { "Great article!" }
2012-01-13 16:44:27 +00:00
end
```
2011-07-01 15:14:27 +00:00
2011-02-07 22:48:29 +00:00
Dependent Attributes
--------------------
2016-02-09 02:34:05 +00:00
Attributes can be based on the values of other attributes using the evaluator
that is yielded to dynamic attribute blocks:
2011-02-07 22:48:29 +00:00
2012-01-13 16:44:27 +00:00
```ruby
factory :user do
2018-08-15 18:19:11 +00:00
first_name { "Joe" }
last_name { "Blow" }
2012-01-13 16:44:27 +00:00
email { "#{first_name}.#{last_name}@example.com".downcase }
end
2011-02-07 22:48:29 +00:00
2013-12-13 15:02:23 +00:00
create(:user, last_name: "Doe").email
2012-01-13 16:44:27 +00:00
# => "joe.doe@example.com"
```
2011-02-07 22:48:29 +00:00
2011-08-20 22:05:41 +00:00
Transient Attributes
--------------------
There may be times where your code can be DRYed up by passing in transient attributes to factories.
2012-01-13 16:44:27 +00:00
```ruby
factory :user do
2014-04-28 21:39:44 +00:00
transient do
2018-08-15 18:19:11 +00:00
rockstar { true }
upcased { false }
2012-01-13 16:44:27 +00:00
end
2011-08-20 22:05:41 +00:00
2018-08-15 18:19:11 +00:00
name { "John Doe#{" - Rockstar" if rockstar}" }
2012-01-13 16:44:27 +00:00
email { "#{name.downcase}@example.com" }
2011-08-20 22:05:41 +00:00
2012-05-04 20:48:46 +00:00
after(:create) do |user, evaluator|
2012-02-08 15:17:57 +00:00
user.name.upcase! if evaluator.upcased
2012-01-13 16:44:27 +00:00
end
end
2011-08-20 22:05:41 +00:00
2013-12-13 15:02:23 +00:00
create(:user, upcased: true).name
2012-01-13 16:44:27 +00:00
#=> "JOHN DOE - ROCKSTAR"
```
2011-08-20 22:05:41 +00:00
2018-09-14 19:02:33 +00:00
Transient attributes will be ignored within attributes\_for and won't be
set on the model,
2014-04-28 21:39:44 +00:00
even if the attribute exists or you attempt to override it.
2011-08-20 22:05:41 +00:00
2017-10-20 19:20:28 +00:00
Within factory_bot's dynamic attributes, you can access transient attributes as
you would expect. If you need to access the evaluator in a factory_bot callback,
2012-02-08 15:17:57 +00:00
you'll need to declare a second block argument (for the evaluator) and access
2014-04-28 21:39:44 +00:00
transient attributes from there.
2011-08-20 22:05:41 +00:00
2016-03-14 19:34:32 +00:00
Method Name / Reserved Word Attributes
-------------------------------
2018-08-31 13:27:31 +00:00
If your attributes conflict with existing methods or reserved words (all methods in the [DefinitionProxy ](https://github.com/thoughtbot/factory_bot/blob/master/lib/factory_bot/definition_proxy.rb ) class) you can define them with `add_attribute` .
2016-03-14 19:34:32 +00:00
```ruby
factory :dna do
add_attribute(:sequence) { 'GATTACA' }
end
factory :payment do
add_attribute(:method) { 'paypal' }
end
```
2016-12-16 10:23:50 +00:00
Inheritance
-----------
You can easily create multiple factories for the same class without repeating common attributes by nesting factories:
```ruby
factory :post do
2018-08-15 18:19:11 +00:00
title { "A title" }
2016-12-16 10:23:50 +00:00
factory :approved_post do
2018-08-15 18:19:11 +00:00
approved { true }
2016-12-16 10:23:50 +00:00
end
end
approved_post = create(:approved_post)
approved_post.title # => "A title"
approved_post.approved # => true
```
You can also assign the parent explicitly:
```ruby
factory :post do
2018-08-15 18:19:11 +00:00
title { "A title" }
2016-12-16 10:23:50 +00:00
end
factory :approved_post, parent: :post do
2018-08-15 18:19:11 +00:00
approved { true }
2016-12-16 10:23:50 +00:00
end
```
As mentioned above, it's good practice to define a basic factory for each class
with only the attributes required to create it. Then, create more specific
factories that inherit from this basic parent. Factory definitions are still
code, so keep them DRY.
2011-02-07 22:48:29 +00:00
Associations
------------
2011-08-25 10:39:54 +00:00
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.
2011-02-07 22:48:29 +00:00
2012-01-13 16:44:27 +00:00
```ruby
factory :post do
# ...
author
end
```
2011-02-07 22:48:29 +00:00
You can also specify a different factory or override attributes:
2012-01-13 16:44:27 +00:00
```ruby
factory :post do
# ...
2012-03-31 15:36:20 +00:00
association :author, factory: :user, last_name: "Writely"
2012-01-13 16:44:27 +00:00
end
```
2011-02-07 22:48:29 +00:00
Default `use_parent_strategy` to true
Background
---
In issues #64 and #66 (from 2010) people expressed surprise
that using the `build` strategy would still `create` any associations.
I remember being similarly surprised by that behavior when I first
started using factory_bot.
The main reason for this behavior is to ensure the built instance will
be valid if there were any foreign key validations
(like `validates_presence_of :user_id`). If we don't save the
associations, there won't be any ids present.
PR #191 (from 2011) offers a workaround for people who don't want
records to be saved automatically. Passing `strategy: :build`
(originally `method: :build`, but later renamed) when declaring the
association will prevent it from being saved when using `build`.
But #191 isn't really a complete solution (as discussed on the PR
after it was merged). `strategy: :build` may do
the right thing when building objects with the `build` strategy, but it
can cause new problems when using the `create` strategy.
A better solution would be something like:
`strategy: <whatever strategy I was already using>`.
PRs #749 and #961 (merged in 2016) introduce something like that,
with the `use_parent_strategy` configuration option.
With this turned on `build` end up being generally [a little faster][]
than `build_stubbed`, since it no longer needs to hit the database for
each association.
[a little faster]: https://gist.github.com/composerinteralia/d4796df9140f431e36f88dfb6fe9733a
I have set `use_parent_strategy` on several projects now. I also added
it to suspenders in thoughtbot/suspenders#952.
On newer projects I have not run into any problems. On existing
projects I have seen the occasional test failure, which are easy enough
to fix by changing `build` to `create`.
Unfortunately I don't think `use_parent_strategy` is widely known,
since it wasn't documented until #1234 (about a month ago).
I also learned in #1234 that the `use_parent_strategy` setting gets
wiped out with `FactoryBot.reload`, which can be problematic when using
factory_bot_rails.
To summarize, we have been exploring having a `build` strategy that uses
`build` all the way down since 2010, but there still isn't a totally
reliable way to get that.
This PR
---
* Default to using the parent strategy for factory_bot 5, as suggested
in #749.
* In the original PR for this (#1240) I had removed
`use_parent_strategy`, but to make the transition smoother I ended up
fixing the reload problem in #1244
Once factory\_bot 5 is released and the dust has settled, it may make
sense to deprecate `use_parent_strategy`, and maybe also the strategy
option for associations.
2019-01-05 00:57:22 +00:00
In factory\_bot 5, associations default to using the same build strategy as
their parent object:
2011-02-07 22:48:29 +00:00
2012-01-13 16:44:27 +00:00
```ruby
Default `use_parent_strategy` to true
Background
---
In issues #64 and #66 (from 2010) people expressed surprise
that using the `build` strategy would still `create` any associations.
I remember being similarly surprised by that behavior when I first
started using factory_bot.
The main reason for this behavior is to ensure the built instance will
be valid if there were any foreign key validations
(like `validates_presence_of :user_id`). If we don't save the
associations, there won't be any ids present.
PR #191 (from 2011) offers a workaround for people who don't want
records to be saved automatically. Passing `strategy: :build`
(originally `method: :build`, but later renamed) when declaring the
association will prevent it from being saved when using `build`.
But #191 isn't really a complete solution (as discussed on the PR
after it was merged). `strategy: :build` may do
the right thing when building objects with the `build` strategy, but it
can cause new problems when using the `create` strategy.
A better solution would be something like:
`strategy: <whatever strategy I was already using>`.
PRs #749 and #961 (merged in 2016) introduce something like that,
with the `use_parent_strategy` configuration option.
With this turned on `build` end up being generally [a little faster][]
than `build_stubbed`, since it no longer needs to hit the database for
each association.
[a little faster]: https://gist.github.com/composerinteralia/d4796df9140f431e36f88dfb6fe9733a
I have set `use_parent_strategy` on several projects now. I also added
it to suspenders in thoughtbot/suspenders#952.
On newer projects I have not run into any problems. On existing
projects I have seen the occasional test failure, which are easy enough
to fix by changing `build` to `create`.
Unfortunately I don't think `use_parent_strategy` is widely known,
since it wasn't documented until #1234 (about a month ago).
I also learned in #1234 that the `use_parent_strategy` setting gets
wiped out with `FactoryBot.reload`, which can be problematic when using
factory_bot_rails.
To summarize, we have been exploring having a `build` strategy that uses
`build` all the way down since 2010, but there still isn't a totally
reliable way to get that.
This PR
---
* Default to using the parent strategy for factory_bot 5, as suggested
in #749.
* In the original PR for this (#1240) I had removed
`use_parent_strategy`, but to make the transition smoother I ended up
fixing the reload problem in #1244
Once factory\_bot 5 is released and the dust has settled, it may make
sense to deprecate `use_parent_strategy`, and maybe also the strategy
option for associations.
2019-01-05 00:57:22 +00:00
FactoryBot.define do
factory :author
factory :post do
author
end
end
post = build(:post)
post.new_record? # => true
post.author.new_record? # => true
post = create(:post)
post.new_record? # => false
post.author.new_record? # => false
```
This is different than the default behavior for previous versions of
factory\_bot, where the association strategy would not always match the strategy
of the parent object. If you want to continue using the old behavior, you can
set the `use_parent_strategy` configuration option to `false` .
```ruby
FactoryBot.use_parent_strategy = false
2012-01-13 16:44:27 +00:00
# Builds and saves a User and a Post
2013-12-13 15:02:23 +00:00
post = create(:post)
2012-01-13 16:44:27 +00:00
post.new_record? # => false
post.author.new_record? # => false
2011-02-07 22:48:29 +00:00
2012-01-13 16:44:27 +00:00
# Builds and saves a User, and then builds but does not save a Post
2013-12-13 15:02:23 +00:00
post = build(:post)
2012-01-13 16:44:27 +00:00
post.new_record? # => true
post.author.new_record? # => false
```
2011-08-10 20:26:29 +00:00
2019-05-31 05:28:37 +00:00
To not save the associated object, specify `strategy: :build` in the factory:
2011-08-10 20:26:29 +00:00
2012-01-13 16:44:27 +00:00
```ruby
Default `use_parent_strategy` to true
Background
---
In issues #64 and #66 (from 2010) people expressed surprise
that using the `build` strategy would still `create` any associations.
I remember being similarly surprised by that behavior when I first
started using factory_bot.
The main reason for this behavior is to ensure the built instance will
be valid if there were any foreign key validations
(like `validates_presence_of :user_id`). If we don't save the
associations, there won't be any ids present.
PR #191 (from 2011) offers a workaround for people who don't want
records to be saved automatically. Passing `strategy: :build`
(originally `method: :build`, but later renamed) when declaring the
association will prevent it from being saved when using `build`.
But #191 isn't really a complete solution (as discussed on the PR
after it was merged). `strategy: :build` may do
the right thing when building objects with the `build` strategy, but it
can cause new problems when using the `create` strategy.
A better solution would be something like:
`strategy: <whatever strategy I was already using>`.
PRs #749 and #961 (merged in 2016) introduce something like that,
with the `use_parent_strategy` configuration option.
With this turned on `build` end up being generally [a little faster][]
than `build_stubbed`, since it no longer needs to hit the database for
each association.
[a little faster]: https://gist.github.com/composerinteralia/d4796df9140f431e36f88dfb6fe9733a
I have set `use_parent_strategy` on several projects now. I also added
it to suspenders in thoughtbot/suspenders#952.
On newer projects I have not run into any problems. On existing
projects I have seen the occasional test failure, which are easy enough
to fix by changing `build` to `create`.
Unfortunately I don't think `use_parent_strategy` is widely known,
since it wasn't documented until #1234 (about a month ago).
I also learned in #1234 that the `use_parent_strategy` setting gets
wiped out with `FactoryBot.reload`, which can be problematic when using
factory_bot_rails.
To summarize, we have been exploring having a `build` strategy that uses
`build` all the way down since 2010, but there still isn't a totally
reliable way to get that.
This PR
---
* Default to using the parent strategy for factory_bot 5, as suggested
in #749.
* In the original PR for this (#1240) I had removed
`use_parent_strategy`, but to make the transition smoother I ended up
fixing the reload problem in #1244
Once factory\_bot 5 is released and the dust has settled, it may make
sense to deprecate `use_parent_strategy`, and maybe also the strategy
option for associations.
2019-01-05 00:57:22 +00:00
FactoryBot.use_parent_strategy = false
2012-01-13 16:44:27 +00:00
factory :post do
# ...
2012-03-31 15:36:20 +00:00
association :author, factory: :user, strategy: :build
2012-01-13 16:44:27 +00:00
end
2011-08-10 20:26:29 +00:00
2012-01-13 16:44:27 +00:00
# Builds a User, and then builds a Post, but does not save either
2013-12-13 15:02:23 +00:00
post = build(:post)
2012-01-13 16:44:27 +00:00
post.new_record? # => true
post.author.new_record? # => true
```
2011-02-07 22:48:29 +00:00
2012-09-07 15:47:39 +00:00
Please note that the `strategy: :build` option must be passed to an explicit call to `association` ,
and cannot be used with implicit associations:
```ruby
factory :post do
# ...
author strategy: :build # << < this does *not* work ; causes author_id to be nil
```
2012-02-17 20:20:46 +00:00
Generating data for a `has_many` relationship is a bit more involved,
depending on the amount of flexibility desired, but here's a surefire example
of generating associated data.
```ruby
2017-10-20 19:20:28 +00:00
FactoryBot.define do
2012-02-17 20:20:46 +00:00
# post factory with a `belongs_to` association for the user
factory :post do
2018-08-15 18:19:11 +00:00
title { "Through the Looking Glass" }
2012-02-17 20:20:46 +00:00
user
end
# user factory without associated posts
factory :user do
2018-08-15 18:19:11 +00:00
name { "John Doe" }
2012-02-17 20:20:46 +00:00
# user_with_posts will create post data after the user has been created
factory :user_with_posts do
2014-04-28 21:39:44 +00:00
# posts_count is declared as a transient attribute and available in
2012-02-17 20:20:46 +00:00
# attributes on the factory, as well as the callback via the evaluator
2014-04-28 21:39:44 +00:00
transient do
2018-08-15 18:19:11 +00:00
posts_count { 5 }
2012-02-17 20:20:46 +00:00
end
2012-05-04 20:48:46 +00:00
# the after(:create) yields two values; the user instance itself and the
2014-04-28 21:39:44 +00:00
# evaluator, which stores all values from the factory, including transient
2012-02-17 20:20:46 +00:00
# attributes; `create_list` 's second argument is the number of records
# to create and we make sure the user is associated properly to the post
2012-05-04 20:48:46 +00:00
after(:create) do |user, evaluator|
2013-12-13 15:02:23 +00:00
create_list(:post, evaluator.posts_count, user: user)
2012-02-17 20:20:46 +00:00
end
end
end
end
```
This allows us to do:
```ruby
2013-12-13 15:02:23 +00:00
create(:user).posts.length # 0
create(:user_with_posts).posts.length # 5
create(:user_with_posts, posts_count: 15).posts.length # 15
2012-02-17 20:20:46 +00:00
```
2016-02-09 02:34:05 +00:00
Generating data for a `has_and_belongs_to_many` relationship is very similar
to the above `has_many` relationship, with a small change, you need to pass an
array of objects to the model's pluralized attribute name rather than a single
2014-03-21 14:14:14 +00:00
object to the singular version of the attribute name.
Here's an example with two models that are related via
2016-02-09 02:34:05 +00:00
`has_and_belongs_to_many` :
2014-03-21 14:14:14 +00:00
```ruby
2017-10-20 19:20:28 +00:00
FactoryBot.define do
2014-03-21 14:14:14 +00:00
# language factory with a `belongs_to` association for the profile
factory :language do
2018-08-15 18:19:11 +00:00
title { "Through the Looking Glass" }
2014-03-21 14:14:14 +00:00
profile
end
# profile factory without associated languages
factory :profile do
2018-08-15 18:19:11 +00:00
name { "John Doe" }
2014-03-21 14:14:14 +00:00
2016-02-09 02:34:05 +00:00
# profile_with_languages will create language data after the profile has
2014-03-21 14:14:14 +00:00
# been created
factory :profile_with_languages do
# languages_count is declared as an ignored attribute and available in
# attributes on the factory, as well as the callback via the evaluator
2016-03-31 21:03:38 +00:00
transient do
2018-08-15 18:19:11 +00:00
languages_count { 5 }
2014-03-21 14:14:14 +00:00
end
2016-02-09 02:34:05 +00:00
# the after(:create) yields two values; the profile instance itself and
# the evaluator, which stores all values from the factory, including
# ignored attributes; `create_list` 's second argument is the number of
# records to create and we make sure the profile is associated properly
2014-03-21 14:14:14 +00:00
# to the language
after(:create) do |profile, evaluator|
create_list(:language, evaluator.languages_count, profiles: [profile])
end
end
end
end
```
This allows us to do:
```ruby
create(:profile).languages.length # 0
create(:profile_with_languages).languages.length # 5
create(:profile_with_languages, languages_count: 15).languages.length # 15
```
2018-11-26 03:41:32 +00:00
Polymorphic associations can be handled with traits:
2019-07-29 14:29:14 +00:00
```ruby
2018-11-26 03:41:32 +00:00
FactoryBot.define do
factory :video
factory :photo
factory :comment do
2019-03-15 18:42:00 +00:00
for_photo # default to the :for_photo trait if none is specified
2018-11-26 03:41:32 +00:00
trait :for_video do
2019-03-15 18:42:00 +00:00
association :commentable, factory: :video
2018-11-26 03:41:32 +00:00
end
trait :for_photo do
2019-03-15 18:42:00 +00:00
association :commentable, factory: :photo
2018-11-26 03:41:32 +00:00
end
end
end
```
This allows us to do:
2019-07-29 14:29:14 +00:00
```ruby
2018-11-26 03:41:32 +00:00
create(:comment)
create(:comment, :for_video)
create(:comment, :for_photo)
```
2011-02-07 22:48:29 +00:00
Sequences
---------
Unique values in a specific format (for example, e-mail addresses) can be
2014-02-26 12:00:42 +00:00
generated using sequences. Sequences are defined by calling `sequence` in a
2011-02-07 22:48:29 +00:00
definition block, and values in a sequence are generated by calling
2013-12-13 15:02:23 +00:00
`generate` :
2011-02-07 22:48:29 +00:00
2012-01-13 16:44:27 +00:00
```ruby
# Defines a new sequence
2017-10-20 19:20:28 +00:00
FactoryBot.define do
2012-01-13 16:44:27 +00:00
sequence :email do |n|
"person#{n}@example.com"
end
end
2011-06-29 15:46:59 +00:00
2013-12-13 15:02:23 +00:00
generate :email
2012-01-13 16:44:27 +00:00
# => "person1@example.com"
2011-06-29 15:46:59 +00:00
2013-12-13 15:02:23 +00:00
generate :email
2012-01-13 16:44:27 +00:00
# => "person2@example.com"
```
2011-02-07 22:48:29 +00:00
2016-02-09 02:34:05 +00:00
Sequences can be used in dynamic attributes:
2011-02-07 22:48:29 +00:00
2012-01-13 16:44:27 +00:00
```ruby
2016-02-09 02:34:05 +00:00
factory :invite do
invitee { generate(:email) }
2012-01-13 16:44:27 +00:00
end
```
2011-02-07 22:48:29 +00:00
2016-02-09 02:34:05 +00:00
Or as implicit attributes:
2011-02-07 22:48:29 +00:00
2012-01-13 16:44:27 +00:00
```ruby
2016-02-09 02:34:05 +00:00
factory :user do
email # Same as `email { generate(:email) }`
2012-01-13 16:44:27 +00:00
end
```
2011-02-07 22:48:29 +00:00
2018-11-26 03:16:22 +00:00
Note that defining sequences as implicit attributes will not work if you have a
factory with the same name as the sequence.
2011-02-07 22:48:29 +00:00
And it's also possible to define an in-line sequence that is only used in
a particular factory:
2012-01-13 16:44:27 +00:00
```ruby
factory :user do
2013-12-15 02:12:33 +00:00
sequence(:email) { |n| "person#{n}@example.com" }
2012-01-13 16:44:27 +00:00
end
```
2011-02-07 22:48:29 +00:00
2011-06-27 21:33:58 +00:00
You can also override the initial value:
2012-01-13 16:44:27 +00:00
```ruby
factory :user do
2013-12-15 02:12:33 +00:00
sequence(:email, 1000) { |n| "person#{n}@example.com" }
2012-01-13 16:44:27 +00:00
end
```
2011-06-27 21:33:58 +00:00
Without a block, the value will increment itself, starting at its initial value:
2012-01-13 16:44:27 +00:00
```ruby
factory :post do
sequence(:position)
end
```
2011-06-27 21:33:58 +00:00
2012-04-01 12:28:13 +00:00
Sequences can also have aliases. The sequence aliases share the same counter:
```ruby
factory :user do
2013-12-15 02:12:33 +00:00
sequence(:email, 1000, aliases: [:sender, :receiver]) { |n| "person#{n}@example.com" }
2012-04-01 12:28:13 +00:00
end
# will increase value counter for :email which is shared by :sender and :receiver
2013-12-13 15:02:23 +00:00
generate(:sender)
2012-04-01 12:28:13 +00:00
```
2012-04-06 18:41:13 +00:00
Define aliases and use default value (1) for the counter
2012-04-01 12:28:13 +00:00
```ruby
factory :user do
2013-12-15 02:12:33 +00:00
sequence(:email, aliases: [:sender, :receiver]) { |n| "person#{n}@example.com" }
2012-04-01 12:28:13 +00:00
end
```
2012-04-06 18:41:13 +00:00
Setting the value:
2012-04-01 12:28:13 +00:00
```ruby
factory :user do
2013-12-15 02:12:33 +00:00
sequence(:email, 'a', aliases: [:sender, :receiver]) { |n| "person#{n}@example.com" }
2012-04-01 12:28:13 +00:00
end
```
2012-04-06 18:41:13 +00:00
The value just needs to support the `#next` method. Here the next value will be 'a', then 'b', etc.
2012-04-01 12:28:13 +00:00
2017-11-03 13:52:46 +00:00
Sequences can also be rewound with `FactoryBot.rewind_sequences` :
```ruby
sequence(:email) {|n| "person#{n}@example.com" }
generate(:email) # "person1@example.com"
generate(:email) # "person2@example.com"
generate(:email) # "person3@example.com"
FactoryBot.rewind_sequences
generate(:email) # "person1@example.com"
```
This rewinds all registered sequences.
2011-08-12 20:16:17 +00:00
Traits
------
2011-08-12 19:25:58 +00:00
2011-08-12 20:16:17 +00:00
Traits allow you to group attributes together and then apply them
2011-08-12 19:25:58 +00:00
to any factory.
2012-01-13 16:44:27 +00:00
```ruby
2012-03-31 15:36:20 +00:00
factory :user, aliases: [:author]
2011-08-12 19:25:58 +00:00
2012-01-13 16:44:27 +00:00
factory :story do
2018-08-15 18:19:11 +00:00
title { "My awesome story" }
2012-01-13 16:44:27 +00:00
author
2011-08-12 19:25:58 +00:00
2012-01-13 16:44:27 +00:00
trait :published do
2018-08-15 18:19:11 +00:00
published { true }
2012-01-13 16:44:27 +00:00
end
2011-08-12 19:25:58 +00:00
2012-01-13 16:44:27 +00:00
trait :unpublished do
2018-08-15 18:19:11 +00:00
published { false }
2012-01-13 16:44:27 +00:00
end
2011-08-12 19:25:58 +00:00
2012-01-13 16:44:27 +00:00
trait :week_long_publishing do
start_at { 1.week.ago }
2018-08-15 18:19:11 +00:00
end_at { Time.now }
2012-01-13 16:44:27 +00:00
end
2011-08-12 19:25:58 +00:00
2012-01-13 16:44:27 +00:00
trait :month_long_publishing do
start_at { 1.month.ago }
2018-08-15 18:19:11 +00:00
end_at { Time.now }
2012-01-13 16:44:27 +00:00
end
2011-08-12 19:25:58 +00:00
2012-03-31 15:36:20 +00:00
factory :week_long_published_story, traits: [:published, :week_long_publishing]
factory :month_long_published_story, traits: [:published, :month_long_publishing]
factory :week_long_unpublished_story, traits: [:unpublished, :week_long_publishing]
factory :month_long_unpublished_story, traits: [:unpublished, :month_long_publishing]
2012-01-13 16:44:27 +00:00
end
```
2011-08-12 19:25:58 +00:00
2018-11-26 03:16:22 +00:00
Traits can be used as implicit attributes:
2011-08-12 19:25:58 +00:00
2012-01-13 16:44:27 +00:00
```ruby
2012-03-31 15:36:20 +00:00
factory :week_long_published_story_with_title, parent: :story do
2012-01-13 16:44:27 +00:00
published
week_long_publishing
2013-02-16 23:24:49 +00:00
title { "Publishing that was started at #{start_at}" }
2012-01-13 16:44:27 +00:00
end
```
2011-08-12 19:25:58 +00:00
2018-11-26 03:16:22 +00:00
Note that defining traits as implicit attributes will not work if you have a
factory or sequence with the same name as the trait.
2011-08-12 20:16:17 +00:00
Traits that define the same attributes won't raise AttributeDefinitionErrors;
the trait that defines the attribute latest gets precedence.
2011-08-12 19:25:58 +00:00
2012-01-13 16:44:27 +00:00
```ruby
factory :user do
2018-08-15 18:19:11 +00:00
name { "Friendly User" }
2012-01-13 16:44:27 +00:00
login { name }
trait :male do
2018-08-15 18:19:11 +00:00
name { "John Doe" }
gender { "Male" }
2012-01-13 16:44:27 +00:00
login { "#{name} (M)" }
end
trait :female do
2018-08-15 18:19:11 +00:00
name { "Jane Doe" }
gender { "Female" }
2012-01-13 16:44:27 +00:00
login { "#{name} (F)" }
end
trait :admin do
2018-08-15 18:19:11 +00:00
admin { true }
2012-01-13 16:44:27 +00:00
login { "admin-#{name}" }
end
2012-03-31 15:36:20 +00:00
factory :male_admin, traits: [:male, :admin] # login will be "admin-John Doe"
factory :female_admin, traits: [:admin, :female] # login will be "Jane Doe (F)"
2012-01-13 16:44:27 +00:00
end
```
2011-08-12 19:25:58 +00:00
2011-09-23 17:14:02 +00:00
You can also override individual attributes granted by a trait in subclasses.
2012-01-13 16:44:27 +00:00
```ruby
factory :user do
2018-08-15 18:19:11 +00:00
name { "Friendly User" }
2012-01-13 16:44:27 +00:00
login { name }
2011-09-23 17:14:02 +00:00
2012-01-13 16:44:27 +00:00
trait :male do
2018-08-15 18:19:11 +00:00
name { "John Doe" }
gender { "Male" }
2012-01-13 16:44:27 +00:00
login { "#{name} (M)" }
end
2011-09-23 17:14:02 +00:00
2012-01-13 16:44:27 +00:00
factory :brandon do
male
2018-08-15 18:19:11 +00:00
name { "Brandon" }
2012-01-13 16:44:27 +00:00
end
end
```
2011-09-23 17:14:02 +00:00
2017-10-20 19:20:28 +00:00
Traits can also be passed in as a list of symbols when you construct an instance from factory_bot.
Traits can be added to factories when the factory creates an instance
This allows for traits to be used with normal factories without having
to name every single factory that uses one (or many) traits.
So, instead of creating male_admin and female_admin factories:
FactoryGirl.define do
factory :user do
trait(:admin) { admin true }
trait(:male) { gender "Male" }
trait(:female) { gender "Female" }
factory :male_admin, :traits => [:male, :admin]
factory :female_admin, :traits => [:admin, :female]
end
end
FactoryGirl.create(:male_admin)
FactoryGirl.create(:female_admin)
You could just create a user with those traits assigned:
FactoryGirl.create(:user, :admin, :male)
FactoryGirl.create(:user, :admin, :female)
This can be combined with attribute overrides as expected.
FactoryGirl.create(:user, :admin, :male, :name => "John Doe")
FactoryGirl.create(:user, :admin, :female, :name => "Jane Doe")
2011-11-18 14:25:49 +00:00
2012-01-13 16:44:27 +00:00
```ruby
factory :user do
2018-08-15 18:19:11 +00:00
name { "Friendly User" }
Traits can be added to factories when the factory creates an instance
This allows for traits to be used with normal factories without having
to name every single factory that uses one (or many) traits.
So, instead of creating male_admin and female_admin factories:
FactoryGirl.define do
factory :user do
trait(:admin) { admin true }
trait(:male) { gender "Male" }
trait(:female) { gender "Female" }
factory :male_admin, :traits => [:male, :admin]
factory :female_admin, :traits => [:admin, :female]
end
end
FactoryGirl.create(:male_admin)
FactoryGirl.create(:female_admin)
You could just create a user with those traits assigned:
FactoryGirl.create(:user, :admin, :male)
FactoryGirl.create(:user, :admin, :female)
This can be combined with attribute overrides as expected.
FactoryGirl.create(:user, :admin, :male, :name => "John Doe")
FactoryGirl.create(:user, :admin, :female, :name => "Jane Doe")
2011-11-18 14:25:49 +00:00
2012-01-13 16:44:27 +00:00
trait :male do
2018-08-15 18:19:11 +00:00
name { "John Doe" }
gender { "Male" }
2012-01-13 16:44:27 +00:00
end
Traits can be added to factories when the factory creates an instance
This allows for traits to be used with normal factories without having
to name every single factory that uses one (or many) traits.
So, instead of creating male_admin and female_admin factories:
FactoryGirl.define do
factory :user do
trait(:admin) { admin true }
trait(:male) { gender "Male" }
trait(:female) { gender "Female" }
factory :male_admin, :traits => [:male, :admin]
factory :female_admin, :traits => [:admin, :female]
end
end
FactoryGirl.create(:male_admin)
FactoryGirl.create(:female_admin)
You could just create a user with those traits assigned:
FactoryGirl.create(:user, :admin, :male)
FactoryGirl.create(:user, :admin, :female)
This can be combined with attribute overrides as expected.
FactoryGirl.create(:user, :admin, :male, :name => "John Doe")
FactoryGirl.create(:user, :admin, :female, :name => "Jane Doe")
2011-11-18 14:25:49 +00:00
2012-01-13 16:44:27 +00:00
trait :admin do
2018-08-15 18:19:11 +00:00
admin { true }
2012-01-13 16:44:27 +00:00
end
end
Traits can be added to factories when the factory creates an instance
This allows for traits to be used with normal factories without having
to name every single factory that uses one (or many) traits.
So, instead of creating male_admin and female_admin factories:
FactoryGirl.define do
factory :user do
trait(:admin) { admin true }
trait(:male) { gender "Male" }
trait(:female) { gender "Female" }
factory :male_admin, :traits => [:male, :admin]
factory :female_admin, :traits => [:admin, :female]
end
end
FactoryGirl.create(:male_admin)
FactoryGirl.create(:female_admin)
You could just create a user with those traits assigned:
FactoryGirl.create(:user, :admin, :male)
FactoryGirl.create(:user, :admin, :female)
This can be combined with attribute overrides as expected.
FactoryGirl.create(:user, :admin, :male, :name => "John Doe")
FactoryGirl.create(:user, :admin, :female, :name => "Jane Doe")
2011-11-18 14:25:49 +00:00
2012-01-13 16:44:27 +00:00
# creates an admin user with gender "Male" and name "Jon Snow"
2013-12-13 15:02:23 +00:00
create(:user, :admin, :male, name: "Jon Snow")
2012-01-13 16:44:27 +00:00
```
Traits can be added to factories when the factory creates an instance
This allows for traits to be used with normal factories without having
to name every single factory that uses one (or many) traits.
So, instead of creating male_admin and female_admin factories:
FactoryGirl.define do
factory :user do
trait(:admin) { admin true }
trait(:male) { gender "Male" }
trait(:female) { gender "Female" }
factory :male_admin, :traits => [:male, :admin]
factory :female_admin, :traits => [:admin, :female]
end
end
FactoryGirl.create(:male_admin)
FactoryGirl.create(:female_admin)
You could just create a user with those traits assigned:
FactoryGirl.create(:user, :admin, :male)
FactoryGirl.create(:user, :admin, :female)
This can be combined with attribute overrides as expected.
FactoryGirl.create(:user, :admin, :male, :name => "John Doe")
FactoryGirl.create(:user, :admin, :female, :name => "Jane Doe")
2011-11-18 14:25:49 +00:00
This ability works with `build` , `build_stubbed` , `attributes_for` , and `create` .
2012-02-07 15:19:22 +00:00
`create_list` and `build_list` methods are supported as well. Just remember to pass
the number of instances to create/build as second parameter, as documented in the
"Building or Creating Multiple Records" section of this file.
```ruby
factory :user do
2018-08-15 18:19:11 +00:00
name { "Friendly User" }
2012-02-07 15:19:22 +00:00
trait :admin do
2018-08-15 18:19:11 +00:00
admin { true }
2012-02-07 15:19:22 +00:00
end
end
# creates 3 admin users with gender "Male" and name "Jon Snow"
2013-12-13 15:02:23 +00:00
create_list(:user, 3, :admin, :male, name: "Jon Snow")
2012-02-07 15:19:22 +00:00
```
2012-08-02 14:19:17 +00:00
Traits can be used with associations easily too:
2012-02-07 15:19:22 +00:00
2012-08-02 14:19:17 +00:00
```ruby
factory :user do
2018-08-15 18:19:11 +00:00
name { "Friendly User" }
2012-08-02 14:19:17 +00:00
trait :admin do
2018-08-15 18:19:11 +00:00
admin { true }
2012-08-02 14:19:17 +00:00
end
end
factory :post do
association :user, :admin, name: 'John Doe'
end
2012-10-15 09:11:04 +00:00
# creates an admin user with name "John Doe"
2013-12-13 15:02:23 +00:00
create(:post).user
2012-08-02 14:19:17 +00:00
```
When you're using association names that're different than the factory:
```ruby
factory :user do
2018-08-15 18:19:11 +00:00
name { "Friendly User" }
2012-08-02 14:19:17 +00:00
trait :admin do
2018-08-15 18:19:11 +00:00
admin { true }
2012-08-02 14:19:17 +00:00
end
end
factory :post do
association :author, :admin, factory: :user, name: 'John Doe'
# or
association :author, factory: [:user, :admin], name: 'John Doe'
end
2012-10-15 09:11:04 +00:00
# creates an admin user with name "John Doe"
2013-12-13 15:02:23 +00:00
create(:post).author
2012-08-02 14:19:17 +00:00
```
2013-04-24 18:51:26 +00:00
2016-03-19 20:20:20 +00:00
Traits can be used within other traits to mix in their attributes.
2013-04-24 18:51:26 +00:00
2013-09-04 16:29:47 +00:00
```ruby
2016-03-19 20:38:37 +00:00
factory :order do
trait :completed do
completed_at { 3.days.ago }
end
2013-04-24 18:51:26 +00:00
2016-03-19 20:38:37 +00:00
trait :refunded do
completed
refunded_at { 1.day.ago }
2013-04-24 18:51:26 +00:00
end
end
```
2016-03-19 20:20:20 +00:00
Finally, traits can accept transient attributes.
```ruby
factory :invoice do
trait :with_amount do
transient do
2018-08-15 18:19:11 +00:00
amount { 1 }
2016-03-19 20:20:20 +00:00
end
after(:create) do |invoice, evaluator|
create :line_item, invoice: invoice, amount: evaluator.amount
end
end
end
create :invoice, :with_amount, amount: 2
```
2011-02-07 22:48:29 +00:00
Callbacks
---------
2017-10-20 19:20:28 +00:00
factory\_bot makes available four callbacks for injecting some code:
2011-02-07 22:48:29 +00:00
2017-10-20 19:20:28 +00:00
* after(:build) - called after a factory is built (via `FactoryBot.build` , `FactoryBot.create` )
* before(:create) - called before a factory is saved (via `FactoryBot.create` )
* after(:create) - called after a factory is saved (via `FactoryBot.create` )
* after(:stub) - called after a factory is stubbed (via `FactoryBot.build_stubbed` )
2011-02-07 22:48:29 +00:00
Examples:
2012-01-13 16:44:27 +00:00
```ruby
# Define a factory that calls the generate_hashed_password method after it is built
factory :user do
2012-05-04 20:48:46 +00:00
after(:build) { |user| generate_hashed_password(user) }
2012-01-13 16:44:27 +00:00
end
```
2011-02-07 22:48:29 +00:00
2011-07-01 15:07:02 +00:00
Note that you'll have an instance of the user in the block. This can be useful.
2011-02-07 22:48:29 +00:00
You can also define multiple types of callbacks on the same factory:
2012-01-13 16:44:27 +00:00
```ruby
factory :user do
2012-05-04 20:48:46 +00:00
after(:build) { |user| do_something_to(user) }
after(:create) { |user| do_something_else_to(user) }
2012-01-13 16:44:27 +00:00
end
```
2011-02-07 22:48:29 +00:00
Factories can also define any number of the same kind of callback. These callbacks will be executed in the order they are specified:
2012-01-13 16:44:27 +00:00
```ruby
factory :user do
2012-05-04 20:48:46 +00:00
after(:create) { this_runs_first }
after(:create) { then_this }
2012-01-13 16:44:27 +00:00
end
```
2011-02-07 22:48:29 +00:00
2013-12-13 15:02:23 +00:00
Calling `create` will invoke both `after_build` and `after_create` callbacks.
2011-02-07 22:48:29 +00:00
Also, like standard attributes, child factories will inherit (and can also define) callbacks from their parent factory.
2012-09-11 15:08:44 +00:00
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).
```ruby
factory :user do
callback(:after_stub, :before_create) { do_something }
after(:stub, :create) { do_something_else }
before(:create, :custom) { do_a_third_thing }
end
```
2013-02-08 16:00:22 +00:00
To override callbacks for all factories, define them within the
2017-10-20 19:20:28 +00:00
`FactoryBot.define` block:
2013-02-08 16:00:22 +00:00
```ruby
2017-10-20 19:20:28 +00:00
FactoryBot.define do
2013-12-15 02:12:33 +00:00
after(:build) { |object| puts "Built #{object}" }
after(:create) { |object| AuditLog.create(attrs: object.attributes) }
2013-02-08 16:00:22 +00:00
factory :user do
2018-08-15 18:19:11 +00:00
name { "John Doe" }
2013-02-08 16:00:22 +00:00
end
end
```
2013-04-02 11:51:47 +00:00
You can also call callbacks that rely on `Symbol#to_proc` :
```ruby
# app/models/user.rb
class User < ActiveRecord::Base
def confirm!
# confirm the user account
end
end
# spec/factories.rb
2017-10-20 19:20:28 +00:00
FactoryBot.define do
2013-04-02 11:51:47 +00:00
factory :user do
after :create, & :confirm!
end
end
2013-12-13 15:02:23 +00:00
create(:user) # creates the user and confirms it
2013-04-02 11:51:47 +00:00
```
2011-09-02 16:05:00 +00:00
Modifying factories
-------------------
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
modify that factory instead of creating a child factory and adding attributes there.
If a gem were to give you a User factory:
2012-01-13 16:44:27 +00:00
```ruby
2017-10-20 19:20:28 +00:00
FactoryBot.define do
2012-01-13 16:44:27 +00:00
factory :user do
2019-03-17 16:36:10 +00:00
full_name { "John Doe" }
2013-12-15 02:12:33 +00:00
sequence(:username) { |n| "user#{n}" }
2018-08-15 18:19:11 +00:00
password { "password" }
2012-01-13 16:44:27 +00:00
end
end
```
2011-09-02 16:05:00 +00:00
Instead of creating a child factory that added additional attributes:
2012-01-13 16:44:27 +00:00
```ruby
2017-10-20 19:20:28 +00:00
FactoryBot.define do
2012-03-31 15:36:20 +00:00
factory :application_user, parent: :user do
2018-08-15 18:19:11 +00:00
full_name { "Jane Doe" }
2012-01-13 16:44:27 +00:00
date_of_birth { 21.years.ago }
2018-08-15 18:19:11 +00:00
gender { "Female" }
health { 90 }
2012-01-13 16:44:27 +00:00
end
end
```
2011-09-02 16:05:00 +00:00
You could modify that factory instead.
2012-01-13 16:44:27 +00:00
```ruby
2017-10-20 19:20:28 +00:00
FactoryBot.modify do
2012-01-13 16:44:27 +00:00
factory :user do
2018-08-15 18:19:11 +00:00
full_name { "Jane Doe" }
2012-01-13 16:44:27 +00:00
date_of_birth { 21.years.ago }
2018-08-15 18:19:11 +00:00
gender { "Female" }
health { 90 }
2012-01-13 16:44:27 +00:00
end
end
```
2011-09-02 16:05:00 +00:00
When modifying a factory, you can change any of the attributes you want (aside from callbacks).
2017-10-20 19:20:28 +00:00
`FactoryBot.modify` must be called outside of a `FactoryBot.define` block as it operates on factories differently.
2011-09-02 16:05:00 +00:00
2011-09-23 17:14:02 +00:00
A caveat: you can only modify factories (not sequences or traits) and callbacks *still compound as they normally would* . So, if
2012-05-04 20:48:46 +00:00
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.
2011-09-02 16:05:00 +00:00
2011-01-04 21:12:04 +00:00
Building or Creating Multiple Records
-------------------------------------
Sometimes, you'll want to create or build multiple instances of a factory at once.
2012-01-13 16:44:27 +00:00
```ruby
2013-12-13 15:02:23 +00:00
built_users = build_list(:user, 25)
created_users = create_list(:user, 25)
2012-01-13 16:44:27 +00:00
```
2011-01-04 21:12:04 +00:00
These methods will build or create a specific amount of factories and return them as an array.
To set the attributes for each of the factories, you can pass in a hash as you normally would.
2012-01-13 16:44:27 +00:00
```ruby
2013-12-13 15:02:23 +00:00
twenty_year_olds = build_list(:user, 25, date_of_birth: 20.years.ago)
2012-01-13 16:44:27 +00:00
```
2011-01-04 21:12:04 +00:00
2016-08-11 15:12:54 +00:00
`build_stubbed_list` will give you fully stubbed out instances:
```ruby
stubbed_users = build_stubbed_list(:user, 25) # array of stubbed users
```
2013-10-25 19:50:58 +00:00
There's also a set of `*_pair` methods for creating two records at a time:
```ruby
2013-12-13 15:02:23 +00:00
built_users = build_pair(:user) # array of two built users
created_users = create_pair(:user) # array of two created users
2013-10-25 19:50:58 +00:00
```
2016-08-11 15:12:54 +00:00
If you need multiple attribute hashes, `attributes_for_list` will generate them:
```ruby
users_attrs = attributes_for_list(:user, 25) # array of attribute hashes
```
2015-02-25 15:54:10 +00:00
Linting Factories
-----------------
2017-10-20 19:20:28 +00:00
factory_bot allows for linting known factories:
2015-02-25 15:54:10 +00:00
```ruby
2017-10-20 19:20:28 +00:00
FactoryBot.lint
2015-02-25 15:54:10 +00:00
```
2017-10-20 19:20:28 +00:00
`FactoryBot.lint` creates each factory and catches any exceptions raised
during the creation process. `FactoryBot::InvalidFactoryError` is raised with
2015-02-25 15:54:10 +00:00
a list of factories (and corresponding exceptions) for factories which could
2015-05-08 14:04:03 +00:00
not be created.
2017-10-20 19:20:28 +00:00
Recommended usage of `FactoryBot.lint`
2015-05-08 14:04:03 +00:00
is to run this in a task
before your test suite is executed.
Running it in a `before(:suite)` ,
will negatively impact the performance
of your tests
when running single tests.
2015-08-17 18:51:22 +00:00
Example Rake task:
2015-05-08 14:04:03 +00:00
```ruby
2017-10-20 19:20:28 +00:00
# lib/tasks/factory_bot.rake
namespace :factory_bot do
desc "Verify that all FactoryBot factories are valid"
2015-05-08 14:04:03 +00:00
task lint: :environment do
2019-12-18 23:58:58 +00:00
if Rails.env.test?
2019-04-17 12:54:50 +00:00
conn = ActiveRecord::Base.connection
conn.transaction do
2017-10-20 19:20:28 +00:00
FactoryBot.lint
2019-04-17 12:54:50 +00:00
raise ActiveRecord::Rollback
2015-05-08 14:04:03 +00:00
end
else
2017-10-20 19:20:28 +00:00
system("bundle exec rake factory_bot:lint RAILS_ENV='test'")
2018-02-01 14:38:32 +00:00
fail if $?.exitstatus.nonzero?
2015-02-25 15:54:10 +00:00
end
end
end
```
2017-10-20 19:20:28 +00:00
After calling `FactoryBot.lint` , you'll likely want to clear out the
2015-02-25 15:54:10 +00:00
database, as records will most likely be created. The provided example above
2019-04-17 12:54:50 +00:00
uses an sql transaction and rollback to leave the database clean.
2015-02-25 15:54:10 +00:00
You can lint factories selectively by passing only factories you want linted:
```ruby
2017-10-20 19:20:28 +00:00
factories_to_lint = FactoryBot.factories.reject do |factory|
2015-02-25 15:54:10 +00:00
factory.name =~ /^old_/
end
2017-10-20 19:20:28 +00:00
FactoryBot.lint factories_to_lint
2015-02-25 15:54:10 +00:00
```
This would lint all factories that aren't prefixed with `old_` .
2016-02-09 02:34:05 +00:00
Traits can also be linted. This option verifies that each
and every trait of a factory generates a valid object on its own.
2015-08-01 03:07:49 +00:00
This is turned on by passing `traits: true` to the `lint` method:
```ruby
2017-10-20 19:20:28 +00:00
FactoryBot.lint traits: true
2015-08-01 03:07:49 +00:00
```
This can also be combined with other arguments:
```ruby
2017-10-20 19:20:28 +00:00
FactoryBot.lint factories_to_lint, traits: true
2015-08-01 03:07:49 +00:00
```
2017-09-28 12:22:16 +00:00
You can also specify the strategy used for linting:
```ruby
2017-10-20 19:20:28 +00:00
FactoryBot.lint strategy: :build
2017-09-28 12:22:16 +00:00
```
2018-11-21 20:28:28 +00:00
Verbose linting will include full backtraces for each error, which can be
helpful for debugging:
```ruby
2019-02-04 03:48:03 +00:00
FactoryBot.lint verbose: true
2018-11-21 20:28:28 +00:00
```
2012-01-20 18:04:48 +00:00
Custom Construction
-------------------
2017-10-20 19:20:28 +00:00
If you want to use factory_bot to construct an object where some attributes
2012-01-23 14:51:14 +00:00
are passed to `initialize` or if you want to do something other than simply
calling `new` on your build class, you can override the default behavior by
2012-04-19 19:42:25 +00:00
defining `initialize_with` on your factory. Example:
2012-01-20 18:04:48 +00:00
```ruby
# user.rb
class User
attr_accessor :name, :email
def initialize(name)
@name = name
end
end
# factories.rb
2013-12-15 02:12:33 +00:00
sequence(:email) { |n| "person#{n}@example.com" }
2012-01-20 18:04:48 +00:00
factory :user do
2018-08-15 18:19:11 +00:00
name { "Jane Doe" }
2012-01-20 18:04:48 +00:00
email
2014-03-07 19:51:30 +00:00
2012-04-24 03:48:33 +00:00
initialize_with { new(name) }
2012-01-20 18:04:48 +00:00
end
2013-12-13 15:02:23 +00:00
build(:user).name # Jane Doe
2012-01-20 18:04:48 +00:00
```
2017-10-20 19:20:28 +00:00
Although factory_bot is written to work with ActiveRecord out of the box, it
2014-09-23 17:18:15 +00:00
can also work with any Ruby class. For maximum compatibility with ActiveRecord,
2014-02-26 12:00:42 +00:00
the default initializer builds all instances by calling `new` on your build class
2012-01-23 14:51:14 +00:00
without any arguments. It then calls attribute writer methods to assign all the
attribute values. While that works fine for ActiveRecord, it actually doesn't
work for almost any other Ruby class.
You can override the initializer in order to:
* Build non-ActiveRecord objects that require arguments to `initialize`
* Use a method other than `new` to instantiate the instance
* Do crazy things like decorate the instance after it's built
2012-04-24 03:48:33 +00:00
When using `initialize_with` , you don't have to declare the class itself when
calling `new` ; however, any other class methods you want to call will have to
be called on the class explicitly.
For example:
```ruby
factory :user do
2018-08-15 18:19:11 +00:00
name { "John Doe" }
2012-04-24 03:48:33 +00:00
initialize_with { User.build_with_name(name) }
end
```
2012-06-08 18:04:41 +00:00
You can also access all public attributes within the `initialize_with` block
by calling `attributes` :
```ruby
factory :user do
2014-04-28 21:39:44 +00:00
transient do
2018-08-15 18:19:11 +00:00
comments_count { 5 }
2012-06-08 18:04:41 +00:00
end
2012-07-07 02:57:11 +00:00
name "John Doe"
2012-06-08 18:04:41 +00:00
initialize_with { new(attributes) }
end
```
This will build a hash of all attributes to be passed to `new` . It won't
2014-04-28 21:39:44 +00:00
include transient attributes, but everything else defined in the factory will be
2018-06-12 19:49:36 +00:00
passed (associations, evaluated sequences, etc.)
2012-06-08 18:04:41 +00:00
2012-05-12 22:53:17 +00:00
You can define `initialize_with` for all factories by including it in the
2017-10-20 19:20:28 +00:00
`FactoryBot.define` block:
2012-05-12 22:53:17 +00:00
```ruby
2017-10-20 19:20:28 +00:00
FactoryBot.define do
2012-05-12 22:53:17 +00:00
initialize_with { new("Awesome first argument") }
end
```
2012-07-27 18:10:38 +00:00
When using `initialize_with` , attributes accessed from within the `initialize_with`
block are assigned *only* in the constructor; this equates to roughly the
following code:
2012-05-18 18:28:51 +00:00
2012-07-27 18:10:38 +00:00
```ruby
2017-10-20 19:20:28 +00:00
FactoryBot.define do
2012-07-27 18:10:38 +00:00
factory :user do
initialize_with { new(name) }
name { 'value' }
end
end
2013-12-13 15:02:23 +00:00
build(:user)
2012-07-27 18:10:38 +00:00
# runs
User.new('value')
```
2017-10-20 19:20:28 +00:00
This prevents duplicate assignment; in versions of factory_bot before 4.0, it
2012-07-27 18:10:38 +00:00
would run this:
2012-05-18 18:28:51 +00:00
2012-07-27 18:10:38 +00:00
```ruby
2017-10-20 19:20:28 +00:00
FactoryBot.define do
2012-07-27 18:10:38 +00:00
factory :user do
initialize_with { new(name) }
name { 'value' }
end
end
2013-12-13 15:02:23 +00:00
build(:user)
2012-07-27 18:10:38 +00:00
# runs
user = User.new('value')
user.name = 'value'
```
2012-05-18 18:28:51 +00:00
2012-04-20 21:22:37 +00:00
Custom Strategies
-----------------
2017-10-20 19:20:28 +00:00
There are times where you may want to extend behavior of factory\_bot by
2012-04-20 21:22:37 +00:00
adding a custom build strategy.
Strategies define two methods: `association` and `result` . `association`
2017-10-20 19:20:28 +00:00
receives a `FactoryBot::FactoryRunner` instance, upon which you can call
2012-04-20 21:22:37 +00:00
`run` , overriding the strategy if you want. The second method, `result` ,
2017-10-20 19:20:28 +00:00
receives a `FactoryBot::Evaluation` instance. It provides a way to trigger
2012-04-20 21:22:37 +00:00
callbacks (with `notify` ), `object` or `hash` (to get the result instance or a
hash based on the attributes defined in the factory), and `create` , which
executes the `to_create` callback defined on the factory.
2017-10-20 19:20:28 +00:00
To understand how factory\_bot uses strategies internally, it's probably
2012-04-20 21:22:37 +00:00
easiest to just view the source for each of the four default strategies.
2012-04-24 20:13:04 +00:00
Here's an example of composing a strategy using
2017-10-20 19:20:28 +00:00
`FactoryBot::Strategy::Create` to build a JSON representation of your model.
2012-04-20 21:22:37 +00:00
```ruby
2012-04-24 15:20:37 +00:00
class JsonStrategy
def initialize
2017-10-20 19:20:28 +00:00
@strategy = FactoryBot.strategy_by_name(:create).new
2012-04-24 15:20:37 +00:00
end
delegate :association, to: :@strategy
2012-04-20 21:22:37 +00:00
def result(evaluation)
2012-04-24 15:20:37 +00:00
@strategy .result(evaluation).to_json
2012-04-20 21:22:37 +00:00
end
end
```
2017-10-20 19:20:28 +00:00
For factory\_bot to recognize the new strategy, you can register it:
2012-04-20 21:22:37 +00:00
```ruby
2017-10-20 19:20:28 +00:00
FactoryBot.register_strategy(:json, JsonStrategy)
2012-04-20 21:22:37 +00:00
```
This allows you to call
```ruby
2017-10-20 19:20:28 +00:00
FactoryBot.json(:user)
2012-04-20 21:22:37 +00:00
```
2017-10-20 19:20:28 +00:00
Finally, you can override factory\_bot's own strategies if you'd like by
2012-04-20 21:22:37 +00:00
registering a new object in place of the strategies.
2012-05-04 20:48:46 +00:00
Custom Callbacks
----------------
Custom callbacks can be defined if you're using custom strategies:
```ruby
class JsonStrategy
def initialize
2017-10-20 19:20:28 +00:00
@strategy = FactoryBot.strategy_by_name(:create).new
2012-05-04 20:48:46 +00:00
end
delegate :association, to: :@strategy
def result(evaluation)
result = @strategy .result(evaluation)
evaluation.notify(:before_json, result)
result.to_json.tap do |json|
evaluation.notify(:after_json, json)
evaluation.notify(:make_json_awesome, json)
end
end
end
2017-10-20 19:20:28 +00:00
FactoryBot.register_strategy(:json, JsonStrategy)
2012-05-04 20:48:46 +00:00
2017-10-20 19:20:28 +00:00
FactoryBot.define do
2012-05-04 20:48:46 +00:00
factory :user do
2013-12-15 02:12:33 +00:00
before(:json) { |user| do_something_to(user) }
after(:json) { |user_json| do_something_to(user_json) }
callback(:make_json_awesome) { |user_json| do_something_to(user_json) }
2012-05-04 20:48:46 +00:00
end
end
```
2012-04-24 03:40:05 +00:00
Custom Methods to Persist Objects
2012-04-24 03:56:38 +00:00
---------------------------------
2012-04-24 03:40:05 +00:00
By default, creating a record will call `save!` on the instance; since this
may not always be ideal, you can override that behavior by defining
`to_create` on the factory:
```ruby
factory :different_orm_model do
2013-12-15 02:12:33 +00:00
to_create { |instance| instance.persist! }
2012-04-24 03:40:05 +00:00
end
```
To disable the persistence method altogether on create, you can `skip_create`
for that factory:
```ruby
factory :user_without_database do
skip_create
end
```
2012-05-12 04:42:44 +00:00
To override `to_create` for all factories, define it within the
2017-10-20 19:20:28 +00:00
`FactoryBot.define` block:
2012-05-12 04:42:44 +00:00
```ruby
2017-10-20 19:20:28 +00:00
FactoryBot.define do
2013-12-15 02:12:33 +00:00
to_create { |instance| instance.persist! }
2012-05-12 04:42:44 +00:00
factory :user do
2018-08-15 18:19:11 +00:00
name { "John Doe" }
2012-05-12 04:42:44 +00:00
end
end
```
2012-04-24 05:03:28 +00:00
ActiveSupport Instrumentation
-----------------------------
In order to track what factories are created (and with what build strategy),
`ActiveSupport::Notifications` are included to provide a way to subscribe to
factories being run. One example would be to track factories based on a
threshold of execution time.
```ruby
2017-10-20 19:20:28 +00:00
ActiveSupport::Notifications.subscribe("factory_bot.run_factory") do |name, start, finish, id, payload|
2012-04-24 05:03:28 +00:00
execution_time_in_seconds = finish - start
if execution_time_in_seconds >= 0.5
$stderr.puts "Slow factory: #{payload[:name]} using strategy #{payload[:strategy]}"
end
end
```
Another example would be tracking all factories and how they're used
throughout your test suite. If you're using RSpec, it's as simple as adding a
`before(:suite)` and `after(:suite)` :
```ruby
2017-10-20 19:20:28 +00:00
factory_bot_results = {}
2012-04-24 05:03:28 +00:00
config.before(:suite) do
2017-10-20 19:20:28 +00:00
ActiveSupport::Notifications.subscribe("factory_bot.run_factory") do |name, start, finish, id, payload|
2012-04-24 05:03:28 +00:00
factory_name = payload[:name]
strategy_name = payload[:strategy]
2017-10-20 19:20:28 +00:00
factory_bot_results[factory_name] ||= {}
factory_bot_results[factory_name][strategy_name] ||= 0
factory_bot_results[factory_name][strategy_name] += 1
2012-04-24 05:03:28 +00:00
end
end
config.after(:suite) do
2017-10-20 19:20:28 +00:00
puts factory_bot_results
2012-04-24 05:03:28 +00:00
end
```
2013-09-12 16:00:47 +00:00
Rails Preloaders and RSpec
--------------------------
2013-10-24 04:25:08 +00:00
When running RSpec with a Rails preloader such as `spring` or `zeus` , it's possible
to encounter an `ActiveRecord::AssociationTypeMismatch` error when creating a factory
2013-09-12 16:00:47 +00:00
with associations, as below:
```ruby
2017-10-20 19:20:28 +00:00
FactoryBot.define do
2019-12-18 23:58:58 +00:00
factory :united_states, class: "Location" do
2018-08-15 18:19:11 +00:00
name { 'United States' }
2013-09-12 16:00:47 +00:00
association :location_group, factory: :north_america
end
2016-02-09 02:34:05 +00:00
2019-12-18 23:58:58 +00:00
factory :north_america, class: "LocationGroup" do
2018-08-15 18:19:11 +00:00
name { 'North America' }
2013-09-12 16:00:47 +00:00
end
end
```
The error occurs during the run of the test suite:
```
2013-12-13 15:02:23 +00:00
Failure/Error: united_states = create(:united_states)
2013-09-12 16:00:47 +00:00
ActiveRecord::AssociationTypeMismatch:
LocationGroup(#70251250797320) expected, got LocationGroup(#70251200725840)
```
The two possible solutions are to either run the suite without the preloader, or
2017-10-20 19:20:28 +00:00
to add `FactoryBot.reload` to the RSpec configuration, like so:
2013-09-12 16:00:47 +00:00
```ruby
RSpec.configure do |config|
2017-10-20 19:20:28 +00:00
config.before(:suite) { FactoryBot.reload }
2013-09-12 16:00:47 +00:00
end
```
2013-12-13 15:02:23 +00:00
Using Without Bundler
---------------------
If you're not using Bundler, be sure to have the gem installed and call:
```ruby
2017-10-20 19:20:28 +00:00
require 'factory_bot'
2013-12-13 15:02:23 +00:00
```
Once required, assuming you have a directory structure of `spec/factories` or
2018-06-12 19:49:36 +00:00
`test/factories` , all you'll need to do is run:
2013-12-13 15:02:23 +00:00
```ruby
2017-10-20 19:20:28 +00:00
FactoryBot.find_definitions
2013-12-13 15:02:23 +00:00
```
If you're using a separate directory structure for your factories, you can
change the definition file paths before trying to find definitions:
```ruby
2017-10-20 19:20:28 +00:00
FactoryBot.definition_file_paths = %w(custom_factories_directory)
FactoryBot.find_definitions
2013-12-13 15:02:23 +00:00
```
If you don't have a separate directory of factories and would like to define
them inline, that's possible as well:
```ruby
2017-10-20 19:20:28 +00:00
require 'factory_bot'
2013-12-13 15:02:23 +00:00
2017-10-20 19:20:28 +00:00
FactoryBot.define do
2013-12-13 15:02:23 +00:00
factory :user do
2018-08-15 18:19:11 +00:00
name { 'John Doe' }
2013-12-13 15:02:23 +00:00
date_of_birth { 21.years.ago }
end
end
```