How do you add factory_bot_rails to a Rails 8.1 app so create(:order) works in Minitest, and where are factory definitions loaded from?
answer
- development and test Gemfile groups
- include FactoryBot::Syntax::Methods
- test/factories or spec/factories
- config.factory_bot.definition_file_paths
- generators write factories, not fixtures
basics
~10 sAdd factory_bot_rails to the development and test groups, include FactoryBot::Syntax::Methods in ActiveSupport::TestCase, and put definitions in test/factories; the railtie loads factories.rb and factories/*.rb under the app root, test/ and spec/.
solid answer
~30 sI add `gem "factory_bot_rails"` to the `:development, :test` group: development so generators pick it up, test so the suite can use it. factory_bot_rails does not add the short methods to Minitest by itself, so in `test/test_helper.rb` I add `include FactoryBot::Syntax::Methods` inside `ActiveSupport::TestCase`. Without that, tests must call `FactoryBot.create(:order)`. In RSpec the same line goes in `RSpec.configure`. The railtie loads definitions after boot from `config.factory_bot.definition_file_paths`, which defaults to `factories`, `test/factories` and `spec/factories`, each as a `.rb` file or a folder searched recursively. From then on `bin/rails generate model Order` writes `test/factories/orders.rb` instead of a YAML fixture, unless `g.factory_bot false` is set.
code
ruby · 15 lines# test/factories/orders.rb
FactoryBot.define do
factory :order do
customer
sequence(:number) { |n| "BM-#{n}" }
end
end
# test/models/order_test.rb
class OrderTest < ActiveSupport::TestCase
test "numbers are unique" do
order = create(:order)
assert_not build(:order, number: order.number).valid?
end
endgo deeper
Know the Gemfile groups, the FactoryBot::Syntax::Methods include, and that factories live in test/factories in a Minitest app.
Explain the railtie's definition paths, the generator's fixture replacement, and how to configure a custom directory correctly.
Set up factories for engines and shared paths, keep generators and loading paths consistent, and add linting to CI.
Decide whether a Rails-default Minitest and fixtures app should adopt factories at all, and how to phase it in without two competing data sources.
## Installing factory_bot itself is framework-agnostic. **factory_bot_rails** wires it into Rails: ```ruby # Gemfile group :development, :test do gem "factory_bot_rails" end ``` - **test** so the suite can build objects; - **development** so `bin/rails generate model` and `scaffold` produce factory files, and so factories can be used from `bin/rails console`. ## Making the methods available The railtie loads the factory definitions, but it does **not** include the short methods into your tests: ```ruby # test/test_helper.rb module ActiveSupport class TestCase parallelize(workers: :number_of_processors) fixtures :all include FactoryBot::Syntax::Methods end end ``` - Because `ActionDispatch::IntegrationTest` and the other Rails test classes subclass `ActiveSupport::TestCase`, they all get `create`, `build`, `build_stubbed`, `attributes_for` and their `_list` and `_pair` forms. - Without the include, call the module methods directly: `FactoryBot.create(:order)`. - With RSpec, the equivalent is `config.include FactoryBot::Syntax::Methods` inside `RSpec.configure`. - `fixtures :all` can stay; it simply loads whatever YAML files remain. ## Where definitions are loaded from `config.factory_bot.definition_file_paths` defaults to `factory_bot`'s list, resolved against `Rails.root`: | Path entry | Files loaded | |---|---| | `factories` | `factories.rb`, `factories/**/*.rb` | | `test/factories` | `test/factories.rb`, `test/factories/**/*.rb` | | `spec/factories` | `spec/factories.rb`, `spec/factories/**/*.rb` | - Definitions are loaded in `after_initialize`, and reloaded in development when the files change. - Add a path, for example from an engine, with `config.factory_bot.definition_file_paths += [...]`; set it to `[]` to switch automatic loading off. - A definition file is plain Ruby inside `FactoryBot.define do ... end`. ## What changes in the generators factory_bot_rails registers itself as the generators' **fixture replacement**: 1. In a Minitest app it sets `fixture: false, fixture_replacement: :factory_bot` on the test framework. 2. `bin/rails generate model Order customer:references number:string` then writes `test/factories/orders.rb` with a starter `factory :order` instead of `test/fixtures/orders.yml`. 3. With rspec-rails as the test framework, the default directory is `spec/factories`. 4. `config.generators { |g| g.factory_bot false }` turns the replacement off; `g.factory_bot dir: "..."` and `suffix: "factory"` change where and how files are named. A custom directory must also be added to `definition_file_paths`, or it will not be loaded. ## Extras worth knowing - `config.factory_bot.file_fixture_support` (on by default) makes `file_fixture("cover.png")` work inside factory blocks, for example to attach an image. - factory_bot_rails 6.5.1 added support for the Rails authentication generator, and its versions track factory_bot's. - Keep definitions small and run `FactoryBot.lint` in CI so a renamed column breaks one clear check instead of hundreds of tests. ## Common setup failures | Symptom | Cause | Fix | |---|---|---| | `NoMethodError: undefined method 'create'` in a test | the `FactoryBot::Syntax::Methods` include is missing | add it to `ActiveSupport::TestCase` | | `KeyError: Factory not registered: "order"` | the definition file is outside the load paths | move it to `test/factories` or extend `definition_file_paths` | | generators still write `test/fixtures/*.yml` | the gem is only in the test group, or `g.factory_bot false` is set | add it to the development group | | a factory edit is not picked up in the console | the console was started before the change | `reload!`, which also reloads factory definitions | ## Using factories outside tests Because the gem is in the development group, `FactoryBot.create(:order, :paid)` works in `bin/rails console` to set up local data quickly. Keep that habit local: factories describe test data, and production code should never depend on them.
- Why should factory_bot_rails sit in the development group and not only in test?Generators run in development. With the gem loaded there, factory_bot_rails registers as the fixture replacement, so `bin/rails generate model` writes a factory file. Factories are also usable from `bin/rails console` for setting up local data. Left only in the test group, generators keep writing YAML fixtures.
- Where should a custom factories directory such as test/support/factories be configured?In `config.factory_bot.definition_file_paths`, so the railtie loads it, for example `config.factory_bot.definition_file_paths << "test/support/factories"` in `config/environments/test.rb`. Setting only the generator option `g.factory_bot dir:` changes where new files are written, not where they are loaded from.
- factory_bot_rails automatically adds create and build to every Minitest test.
- Factories must live in spec/factories even in a Minitest app.
- Adding factory_bot_rails requires deleting test/fixtures and fixtures :all.
- g.factory_bot dir: also tells factory_bot where to load definitions from.
- factory_bot_rails belongs only in the production group of the Gemfile.