FactoryBot Vs. Fixtures: Testing Rails Applications

Compare FactoryBot vs fixtures for Rails test data. Learn how each works, build vs create, performance, and when to choose each.


By Jean Emmanuel Cadet • 28 min read

FactoryBot vs. Fixtures: Testing Rails Applications
Share with friends

You open a new test file, you need a user and a couple of posts, and you stop to ask: should I use Rails fixtures or FactoryBot? It is one of the most common questions in Rails testing, and the honest answer is that both approaches work well when you understand their trade-offs. The FactoryBot vs fixtures debate often sounds like a fight between two camps, but it is really a question about how you want to manage test data in your application.

This guide explains how Rails fixtures and FactoryBot work, where each one shines, and where each one hurts. We will use the same small domain (users, posts, and comments) for every example, so you can compare both approaches side by side in model tests and integration tests. The examples use Rails 8.1 conventions and Rails' built-in Minitest setup, and I will point out where RSpec differs.

By the end, you will be able to pick a test data strategy that fits your project instead of copying whatever your last team used.


Why Test Data Matters in Rails

Every Rails test follows the same basic shape: set up some data, run some behavior, check the result. The setup step is where many test suites quietly go wrong. Test data is not just a detail, it shapes almost every quality of your suite.

Readability. A good test tells a story. When you read it, you should immediately see which data matters and why. If a test depends on a record defined in a file you have never opened, the story has a missing chapter.

Maintainability. Test data is code, and it changes as your schema changes. If adding a required column forces you to edit forty tests, your data strategy is working against you.

Execution speed. Every record you write to the database costs time. A suite that creates hundreds of unnecessary rows per test will slowly become a suite nobody wants to run.

Reliability. Tests should pass or fail for the right reasons. Shared mutable data, hidden dependencies between tests, and order-dependent behavior all produce flaky results.

Rails gives you two common ways to prepare this data. Fixtures are built into Rails: you describe records in YAML files, and Rails loads them into the test database. Factories come from the FactoryBot gem: you describe how to build records in Ruby, and you create them on demand inside each test. Both solve the same problem with very different philosophies, which is why the choice deserves some thought.


What Are Rails Fixtures?

Fixtures are Rails' built-in mechanism for defining sample data for tests. They ship with every Rails application, require no extra gems, and are loaded automatically by the default Minitest setup.

Where Fixtures Live and How They Load

By default, fixtures live in test/fixtures, with one YAML file per table (for example users.yml and posts.yml). When you generate a model with bin/rails generate model, Rails creates a matching fixture file for you.

The generated test/test_helper.rb contains this line inside ActiveSupport::TestCase:

fixtures :all

This tells Rails to load every fixture file before the tests run. If you prefer to be selective, you can list specific fixtures, such as fixtures :users, :posts, in an individual test class.

Here is how loading works in practice:

  • Rails reads the YAML files (after processing ERB), deletes existing rows in the corresponding tables, and inserts the fixture rows directly into the test database.
  • Fixtures are inserted once, outside the per-test transaction. Each test then runs inside a database transaction that is rolled back at the end, so changes made by one test do not leak into the next.
  • Fixture rows are inserted straight into the database. Validations and callbacks do not run.

You access a fixture record in a test by calling a method named after the table, passing the fixture label:

users(:alice)
posts(:published_post)
users(:alice, :bruno) # returns an array of two records

The Models Used in This Article

All examples in this article use three models. Here they are in full, so every later example stays consistent.

# app/models/user.rb
class User < ApplicationRecord
has_secure_password

has_many :posts, foreign_key: :author_id, inverse_of: :author, dependent: :destroy
has_many :comments, foreign_key: :author_id, inverse_of: :author, dependent: :destroy

normalizes :email_address, with: ->(email) { email.strip.downcase }

validates :name, presence: true
validates :email_address, presence: true, uniqueness: true
end
# app/models/post.rb
class Post < ApplicationRecord
belongs_to :author, class_name: "User", inverse_of: :posts
has_many :comments, dependent: :destroy

enum :status, { draft: 0, published: 1, archived: 2 }, default: :draft

validates :title, presence: true, length: { maximum: 120 }
validates :body, presence: true

def publish!
update!(status: :published, published_at: Time.current)
end
end
# app/models/comment.rb
class Comment < ApplicationRecord
belongs_to :post
belongs_to :author, class_name: "User", inverse_of: :comments

validates :body, presence: true
end

A few notes on these models. has_secure_password requires the bcrypt gem and a password_digest column. The enum :status declaration uses the positional syntax, which is the current style, and it gives you helpers such as Post.published and post.published?. The users table has name, email_address, and password_digest columns, and the posts table has title, body, status (integer), published_at, and author_id.

A Realistic Fixture Example

Here are fixtures for users and posts:

# test/fixtures/users.yml
<% password_digest = BCrypt::Password.create("password", cost: 4) %>

alice:
name: Alice Martin
email_address: [email protected]
password_digest: <%= password_digest %>

bruno:
name: Bruno Cadet
email_address: [email protected]
password_digest: <%= password_digest %>
# test/fixtures/posts.yml
published_post:
author: alice
title: Getting Started with Rails Testing
body: A practical introduction to Minitest and fixtures.
status: published
published_at: <%= 2.days.ago.to_fs(:db) %>

draft_post:
author: alice
title: Draft About Factories
body: Still working on this one.
status: draft

bruno_post:
author: bruno
title: Understanding Active Record Callbacks
body: How callbacks run, and when to avoid them.
status: published
published_at: <%= 1.day.ago.to_fs(:db) %>
# test/fixtures/comments.yml
helpful_comment:
post: published_post
author: bruno
body: Great introduction, thanks!

Several things are happening here that are worth understanding.

Fixture Labels, Associations, and References

The top-level key of each record (alice, published_post) is the label. Rails turns each label into a stable integer primary key by hashing it, which you can see with ActiveRecord::FixtureSet.identify(:alice). Because the id is derived from the label, you never write primary keys by hand.

This is also what makes associations easy. In posts.yml, author: alice does not store the string "alice". Rails finds the author association on Post and fills in author_id with the id that alice hashes to. You reference the association name and the label of the other fixture, and Rails does the rest. The same idea works for post: published_post in the comments file.

A few related details:

  • Polymorphic associations use the label plus the type in parentheses, such as imageable: alice (User).
  • Join models for has_many :through relationships can be defined in their own fixture file, named after the join table.
  • Enum values can be written by name (status: published), as in the example above.
  • Rails fills in created_at and updated_at for you if the columns exist and you do not set them.

ERB in Fixtures

Fixture files are processed as ERB before being parsed as YAML. That is why <%= 2.days.ago.to_fs(:db) %> works. ERB is useful for dates, shared values, and generating several similar records:

# test/fixtures/comments.yml (excerpt)
<% 3.times do |i| %>
comment_<%= i %>:
post: published_post
author: bruno
body: Generated comment number <%= i %>
<% end %>

Use this sparingly. A fixture file that is mostly ERB loops can be harder to read than the Ruby code it was meant to replace. You can also use YAML anchors under a special DEFAULTS key to share values between records, and Rails ignores the DEFAULTS entry itself when loading.

Advantages of Fixtures

  • Built in. No gem, no configuration, and the generators create fixture files for you.
  • Loaded once. Rows are inserted a single time per run rather than before every test, so tests start with data already available.
  • Realistic shared dataset. Fixtures give you a small, stable world (an admin, a regular user, a published post) that many tests can read from.
  • Readable relationships. Labels make references between records easy to scan in a YAML file.

Limitations of Fixtures

  • Validations and callbacks are skipped. A fixture can describe a record that your model would never allow, and nothing will tell you.
  • Implicit data. A test that says posts(:draft_post) depends on a file elsewhere. Readers must open the YAML to learn what that record contains.
  • Shared by every test. Because every test sees the same rows, changing a fixture to suit one test can break another.
  • Less flexible for variations. If a test needs a slightly different record, you either add another fixture or build the record in the test.

What Is FactoryBot?

FactoryBot is a Ruby library for building test objects from definitions called factories. Instead of keeping a fixed set of rows in YAML, you describe how to build a valid record once, and then ask for a fresh one whenever a test needs it, overriding only the details that matter to that test.

It is important to be clear about one thing: FactoryBot is not part of Rails. Rails fixtures are built in, while FactoryBot is a third-party gem you add yourself. The Rails-specific integration comes from the factory_bot_rails gem.

Installing and Configuring FactoryBot in Rails

Add the gem to the development and test groups of your Gemfile:

# Gemfile
group :development, :test do
gem "factory_bot_rails"
end

Then run bundle install. The factory_bot_rails gem automatically loads factory definitions from test/factories (and from spec/factories in RSpec projects).

To call build, create, and the other methods without the FactoryBot. prefix in Minitest, include the syntax methods in your test case base class:

# test/test_helper.rb
class ActiveSupport::TestCase
include FactoryBot::Syntax::Methods
end

If you use RSpec, you add the equivalent line to your RSpec configuration instead:

# spec/rails_helper.rb
RSpec.configure do |config|
config.include FactoryBot::Syntax::Methods
end

Everything in this article works with RSpec as well. The factory definitions are identical, and only the test syntax around them changes. (RSpec can also load fixtures, using config.fixture_paths and fixtures :all, so the fixtures-versus-factories decision is independent of your test framework.)

Defining a Basic Factory

A factory is defined inside a FactoryBot.define block:

# test/factories/users.rb
FactoryBot.define do
factory :user do
sequence(:name) { |n| "User #{n}" }
sequence(:email_address) { |n| "user#{n}@example.com" }
password { "password" }
end
end

Each attribute is defined with a block, so the value is evaluated every time a record is built. The sequence helper generates a new value on each call, which is how you satisfy the uniqueness validation on email_address without collisions. The password attribute works because has_secure_password defines a password= writer.

Here are factories for posts and comments:

# test/factories/posts.rb
FactoryBot.define do
factory :post do
association :author, factory: :user
sequence(:title) { |n| "Post title #{n}" }
body { "Body text for the post." }

trait :published do
status { :published }
published_at { 2.days.ago }
end

trait :archived do
status { :archived }
end
end
end
# test/factories/comments.rb
FactoryBot.define do
factory :comment do
post
association :author, factory: :user
body { "Thanks for sharing this." }
end
end

In the :post factory, association :author, factory: :user tells FactoryBot that the author attribute should be filled with a :user factory. You need the factory: :user option here because there is no factory named :author. In the :comment factory, the bare post line is shorthand for an association to the :post factory, since the names match.

Build, Create, Build Stubbed, and Attributes For

FactoryBot gives you several strategies for turning a factory into something you can use. Choosing the right one is the most important FactoryBot skill.

user  = build(:user)          # in memory only, nothing written to the database
user = create(:user) # built, validated, and saved with an INSERT
user = build_stubbed(:user) # fake persisted object, database access is blocked
attrs = attributes_for(:user) # a plain Hash of attributes, no object at all
  • build instantiates the object with new and assigns attributes. No SQL INSERT runs, so it is fast, and you can still call valid? on it.
  • create builds the object and then saves it, so validations and callbacks run and a row is written. Use it when the database must really contain the record.
  • build_stubbed returns an object that looks persisted: it has an id and persisted? returns true. It never touches the database, and calling methods such as save on it raises an error. It suits tests that only need an object to read from.
  • attributes_for returns a hash of the factory's attributes without associations. It is handy for controller or integration tests that post form params, for example post posts_path, params: { post: attributes_for(:post) }.

This is the heart of the FactoryBot build vs create question. When a test only exercises Ruby logic on an object, build or build_stubbed is usually enough. When a test needs to query the database, run a request, or reload a record, you need create.

There is one detail about associations worth knowing. Since FactoryBot 5, an association inherits the strategy of its parent by default. So build(:post) builds the author in memory too, while create(:post) creates the author as well. You can override this on a specific association with the strategy option if you need to.

Traits, Sequences, and Associations in Action

Traits are named groups of attributes that describe a state. You apply them by name, and you can still override individual attributes:

create(:post, :published)
create(:post, :published, title: "Custom title")
create_list(:post, 3, :published, author: create(:user))

Sequences keep unique values unique, as you saw with email addresses. Associations let one factory pull in another, and you can always pass an existing record to replace the default:

alice = create(:user, name: "Alice Martin")
post = create(:post, :published, author: alice)
comment = create(:comment, post: post)

Notice how each line states exactly what is special about that record. That is the main appeal of factories: defaults handle the boring details, and the test names only what it cares about.

Advantages of FactoryBot

  • Explicit data. The test creates what it needs, so the setup sits next to the assertions.
  • Flexible. Overrides, traits, and sequences make it easy to produce many variations of a record.
  • Runs through your model. Because create goes through Active Record, validations and callbacks run, so factories break loudly if they produce invalid data.
  • In-memory options. build and build_stubbed let you avoid the database when it is not needed.
  • Works with any test framework. Minitest and RSpec both work.

Limitations of FactoryBot

  • An extra dependency. It is a gem to install, update, and learn.
  • Per-test cost. Records are created inside each test, so heavy factories add up over a large suite.
  • Hidden complexity. Factories with deep association chains, callbacks, and many traits can become hard to follow.
  • Easy to overuse create. Because it is convenient, it tends to be used where build would do.

FactoryBot vs. Fixtures: Key Differences

Now that you have seen both tools, here is a side-by-side comparison. Treat it as a summary of trade-offs rather than a scoreboard.

Aspect

Rails fixtures

FactoryBot

Setup and configuration

Built into Rails, no gem needed

Requires factory_bot_rails and a small amount of configuration

Readability

Data lives in YAML files, so tests reference labels

Data is created in the test, so setup is visible in place

Flexibility

Fixed records, variations need new fixtures

Overrides, traits, and sequences produce variations easily

Associations

Reference other fixtures by label

Associations built by factory, strategy follows the parent

Reusability

One shared dataset for the whole suite

Reusable definitions, fresh records per test

Database interaction

Inserted once, bypasses validations and callbacks

create saves through Active Record, build and build_stubbed avoid the database

Execution speed

Loading cost is paid up front, per-test cost is low

Cost grows with the number of records created per test

Maintenance

Shared rows can couple unrelated tests

Factories need upkeep and can grow complicated

Complex scenarios

Harder to express many variations

Easier to compose through traits, transients, and callbacks

Where Each Approach Works Particularly Well

Fixtures work particularly well for stable reference data that many tests read but rarely change: roles, plans, countries, and a small set of baseline users. They are also pleasant in smaller applications where a handful of named records covers most scenarios, and they keep the dependency list short.

FactoryBot works particularly well when tests need many different variations of a record, when the data a test needs is specific to that test, or when you want setup to be visible and self-contained. It also helps when models have many required attributes, because the factory fills in the defaults for you.

Neither approach is universally better. A small app with a stable schema can have an excellent fixture-based suite, and a large app with many states and edge cases can have an excellent FactoryBot-based suite. The real risk is not choosing the "wrong" tool, it is using either one carelessly.


Practical Examples: Testing with Both Approaches

Let us put both approaches to work on the same scenario. We will test the Post model and a public posts index, first with fixtures and then with FactoryBot. The goal is to make the differences in setup and readability easy to see.

The Scenario

We want to verify the following behavior:

  • A post is valid with a title, body, and author.
  • A post requires a title.
  • Calling publish! marks a draft as published and sets published_at.
  • The Post.published scope excludes drafts.
  • The public posts page lists published posts and hides drafts.

For the integration tests, assume a public PostsController and a matching route:

# config/routes.rb
resources :posts, only: %i[index show]
# app/controllers/posts_controller.rb
class PostsController < ApplicationController
def index
@posts = Post.published.includes(:author).order(published_at: :desc)
end

def show
@post = Post.published.find(params[:id])
end
end

Assume the index view renders each post title inside an h2 element.

Model Tests with Fixtures

# test/models/post_test.rb
require "test_helper"

class PostTest < ActiveSupport::TestCase
test "is valid with a title, body, and author" do
assert posts(:published_post).valid?
end

test "requires a title" do
post = Post.new(body: "Some text", author: users(:alice))

assert_not post.valid?
assert_includes post.errors[:title], "can't be blank"
end

test "publish! marks a draft as published" do
post = posts(:draft_post)

freeze_time do
post.publish!

assert post.published?
assert_equal Time.current, post.published_at
end
end

test "published scope excludes drafts" do
assert_includes Post.published, posts(:published_post)
assert_not_includes Post.published, posts(:draft_post)
end
end

The freeze_time helper comes from Rails' time helpers, which are available in ActiveSupport::TestCase. The tests are short because the data already exists. The cost is that a reader must open posts.yml to confirm that draft_post really is a draft by the author alice.

Model Tests with FactoryBot

# test/models/post_test.rb
require "test_helper"

class PostTest < ActiveSupport::TestCase
test "is valid with a title, body, and author" do
assert build(:post).valid?
end

test "requires a title" do
post = build(:post, title: nil)

assert_not post.valid?
assert_includes post.errors[:title], "can't be blank"
end

test "publish! marks a draft as published" do
post = create(:post)

freeze_time do
post.publish!

assert post.published?
assert_equal Time.current, post.published_at
end
end

test "published scope excludes drafts" do
published = create(:post, :published)
draft = create(:post)

assert_includes Post.published, published
assert_not_includes Post.published, draft
end
end

Look at how each test chooses its strategy. The validity and title tests use build, because they never need the database. The publish! test uses create because update! needs a persisted record. The scope test uses create because it runs a real query. The setup is a few lines longer, but every test explains its own data.

Integration Tests with Fixtures

# test/integration/posts_flow_test.rb
require "test_helper"

class PostsFlowTest < ActionDispatch::IntegrationTest
test "index lists published posts and hides drafts" do
get posts_path

assert_response :success
assert_select "h2", text: posts(:published_post).title
assert_select "h2", text: posts(:draft_post).title, count: 0
end

test "show returns not found for a draft" do
get post_path(posts(:draft_post))

assert_response :not_found
end
end

The second test expects a 404 because Post.published.find raises ActiveRecord::RecordNotFound, which Rails' default test environment configuration renders as a not found response. If you changed show_exceptions in config/environments/test.rb, adjust the test accordingly.

Integration Tests with FactoryBot

# test/integration/posts_flow_test.rb
require "test_helper"

class PostsFlowTest < ActionDispatch::IntegrationTest
test "index lists published posts and hides drafts" do
published = create(:post, :published)
draft = create(:post, title: "Unpublished draft")

get posts_path

assert_response :success
assert_select "h2", text: published.title
assert_select "h2", text: draft.title, count: 0
end

test "show returns not found for a draft" do
draft = create(:post)

get post_path(draft)

assert_response :not_found
end
end

Integration tests send a real request through the stack, and the controller loads records from the database. That means these tests must use create. A build_stubbed object would not exist in the database, and the request would not find it.

If you also want browser-level coverage of flows like this one, our guide to Rails system tests covers Capybara-based tests that use the same data strategies.

Comparing Setup and Readability

With fixtures, the test bodies are shorter, but the meaning of posts(:draft_post) lives in another file. With FactoryBot, the test is longer, but you can read the whole story in one place. Fixtures optimize for brevity and a shared world, while factories optimize for locality and explicitness. Neither is wrong, and your team's tolerance for jumping between files often decides which feels better.


Handling Associations and Complex Data

Real applications rarely stop at a single table. Here is how each approach handles related records and varying states.

Representing Related Records

With fixtures, relationships are expressed by label, as you saw with author: alice and post: published_post. In a test, you can follow associations through your models as usual:

test "a post knows its comments" do
assert_includes posts(:published_post).comments, comments(:helpful_comment)
end

With FactoryBot, you can pass related records explicitly, or define traits that build them for you. A trait that adds comments to a post can use a transient attribute and an after(:create) callback:

# test/factories/posts.rb (excerpt)
trait :with_comments do
transient do
comments_count { 3 }
end

after(:create) do |post, evaluator|
create_list(:comment, evaluator.comments_count, post: post)
end
end

Now create(:post, :with_comments) produces a post with three comments, and create(:post, :with_comments, comments_count: 5) produces five. A transient attribute is a value that exists only to configure the factory and is not assigned to the model.

Required Attributes and Validations

Validations affect both approaches differently. With FactoryBot, create runs validations, so an invalid factory fails the moment you use it. That is annoying in the moment but valuable, because it keeps your test data honest.

With fixtures, nothing is validated at load time. A fixture missing a required value can silently exist in your test database. A simple safeguard is a test that checks every fixture record you care about:

# test/models/fixture_validity_test.rb
require "test_helper"

class FixtureValidityTest < ActiveSupport::TestCase
test "all post fixtures are valid" do
Post.find_each do |post|
assert post.valid?, "Fixture #{post.title} is invalid: #{post.errors.full_messages.to_sentence}"
end
end
end

FactoryBot offers a built-in equivalent called linting. FactoryBot.lint builds each factory (and, with traits: true, each trait) and raises an error that lists any invalid ones:

# test/factories_test.rb
require "test_helper"

class FactoriesTest < ActiveSupport::TestCase
test "all factories and traits are valid" do
FactoryBot.lint traits: true
end
end

Remember that validations in Rails are only one layer of protection. If you are unsure which rules belong in the model and which in the schema, see our article on database constraints vs. Rails validations, because fixtures bypass validations but not database constraints.

Representing Different States of a Model

A post can be a draft, published, or archived. In fixtures, each state usually becomes its own named record (draft_post, published_post, and so on). That is clear and cheap, but the number of fixtures grows with every state and combination.

In FactoryBot, states become traits (:published, :archived), and you combine them freely. When a combination matters, you can name it explicitly in the test: create(:post, :published, :with_comments).

Avoiding Unnecessarily Complicated Test Data

Whichever approach you choose, a few habits keep data simple:

  • Create the smallest set of records that makes the behavior testable.
  • Give fixtures and traits names that describe state, not identity (draft_post rather than post_three).
  • Override only the attribute that matters to the test, and let defaults handle the rest.
  • Avoid factories that create long chains of associated records by default.

Performance and Test Reliability

Test speed is where many strong opinions appear, so let us stay precise. Neither approach is always faster. What matters is how much data each test actually writes and how much of that data it needs.

How Fixture Loading Works

Fixtures are inserted into the database once, before tests run, and then each test runs inside a transaction. That means the per-test cost of fixtures is small: the rows are already there. The cost shows up elsewhere:

  • Loading time grows with the number of fixture rows, and it is paid again for each database when you run tests in parallel (Rails gives each parallel worker its own test database).
  • Every test sees every fixture, whether it needs them or not. A very large fixture set can make queries and counts harder to reason about.

If you use many fixtures, keep them small and focused, and consider loading only the files a test class needs with fixtures :users, :posts.

How FactoryBot Can Slow a Suite Down

FactoryBot does its work during the test. Each create call runs validations, callbacks, and one or more INSERT statements. The cost is easy to miss when a factory creates associated records, because a single create(:comment) may insert a comment, a post, and two users.

The impact multiplies across a large suite. Common culprits include:

  • Using create where build would do.
  • Factories whose associations create more records than the test needs.
  • Traits or callbacks that quietly insert extra rows.

Reducing Database Use with Build and Build Stubbed

Whenever a test only needs a Ruby object, prefer the cheaper strategies:

test "full title includes the author name" do
post = build_stubbed(:post)

assert_match post.author.name, post.byline
end

(This example assumes a byline method on Post.) build_stubbed avoids the database entirely, and it also builds the author as a stub, because associations follow the parent strategy.

There are limits. build_stubbed objects cannot be saved or queried, so they will not work for tests that run scopes, request specs, or anything that reloads records. Use the cheapest strategy that still makes the test honest.

Test Isolation, Cleanup, and Shared State

Rails wraps each test in a transaction and rolls it back afterward. In a standard Rails Minitest setup, this is the default, and it covers both fixture-based changes and records you create with FactoryBot inside a test. You do not usually need an extra cleanup gem for this.

The real isolation risks are more subtle:

  • Mutating shared fixtures. Changes to a fixture record inside a test are rolled back, but tests that assume a fixture has a particular value can break when someone edits the YAML for another purpose.
  • Data created outside a test. Records created at class load time, in test_helper.rb, or in seeds are not covered by the per-test transaction and can persist across tests.
  • Order dependence. Tests should pass in any order. Rails randomizes test order by default, which helps expose hidden dependencies.

To find out where your time actually goes, measure it. The Rails test runner can list the slowest tests with bin/rails test --profile, which gives you real numbers instead of guesses.


Common Mistakes and Best Practices

Most test data problems come from habits, not from the tools. Here are the mistakes I see most often, with fixes.

Creating Too Much Test Data

If a test needs one user, do not create a whole organization. Extra data slows the test and distracts the reader. Start with the minimum, and add only when a failing assertion demands it.

Using Factories When an In-Memory Object Would Be Enough

A validation test does not need a saved record:

# Wasteful
post = create(:post, title: nil) # raises, because create validates

# Better
post = build(:post, title: nil)
assert_not post.valid?

Using build (or build_stubbed) when the database is irrelevant keeps tests fast and focused.

Defining Overly Complex Factories

A factory that creates five associations, runs three callbacks, and has a dozen traits becomes its own codebase. Keep the base factory minimal: the smallest set of attributes that produces a valid record. Move optional complexity into explicit traits.

Relying on Implicit or Unclear Fixture References

users(:user_one) tells the reader nothing. Name fixtures after their role or state (alice_admin, draft_post), so tests read like sentences, and avoid reusing a fixture for purposes its name does not suggest.

Creating Unnecessary Database Records

Watch for hidden inserts: associations that create extra rows, after(:create) callbacks, and create_list calls with large counts. When a suite slows down, count the INSERTs, not the tests.

Making Tests Depend on Shared Mutable Data

If one test changes a record that another test relies on, you get failures that depend on order. Treat shared fixtures as read-only reference data. If a test needs to change something, create or build a fresh record for that test.

Using Factories to Hide Important Test Setup

A factory should supply boring defaults, not hide the facts that make the test meaningful. Compare:

# Hides what matters
post = create(:post, :ready_for_review)

# Shows what matters
post = create(:post, :published, published_at: 8.days.ago)

If a test's outcome depends on an attribute, that attribute should appear in the test.

Keeping Test Data Focused on the Behavior Being Tested

Every record in a test should earn its place. Ask: if I remove this record, does the test still prove the same thing? If yes, remove it. Focused data makes failures easier to diagnose and tests easier to read.


Can You Use FactoryBot and Fixtures Together?

Yes. Fixtures are part of Rails, FactoryBot is a separate gem, and they do not conflict. Many teams use both, and the combination can be a good fit when each tool does what it does best.

Situations Where Combining Them Makes Sense

  • Stable reference data in fixtures. Roles, plans, categories, and a few baseline users rarely change and benefit from being loaded once.
  • Scenario-specific data in factories. Posts in particular states, orders with specific line items, and edge cases are easier to express with traits and overrides.
  • Gradual migration. A team moving from one approach to the other can run both while converting tests incrementally.

Establishing Clear Conventions

The danger of mixing is inconsistency. If some tests use users(:alice) and others use create(:user) for no clear reason, new developers will not know which to pick. A few conventions prevent this:

  • One source per model. If User is defined in fixtures, do not also define a :user factory. Keep each model in one place.
  • Document the rule. Add a short section to your contributing guide explaining which tool is used for what.
  • Prefer explicit data in feature-specific tests. Reach for the shared dataset only for reference data.
  • Configure generators to match. You can stop Rails from generating fixture files if your team does not use them for a model, and our guide to custom Rails generators shows how to automate other team conventions.
# config/application.rb
config.generators do |g|
g.test_framework :test_unit, fixture: false
end

A Realistic Balanced Approach

Imagine a project where users are stable reference data kept in fixtures (users.yml as shown earlier), and posts are created by factories, so there is no posts.yml. A test can combine them naturally:

# test/models/user_test.rb
require "test_helper"

class UserTest < ActiveSupport::TestCase
test "published posts only counts posts that are published" do
alice = users(:alice)

create(:post, :published, author: alice)
create(:post, author: alice)

assert_equal 1, alice.posts.published.count
end
end

Here users(:alice) supplies a stable, shared baseline, while the posts are created for this exact scenario. The test reads clearly, creates only two records, and does not depend on any hidden posts. The :post factory still builds its own author by default, but this test overrides it with alice, which respects the "one source per model" rule for Post.


Which Should You Choose?

There is no universal winner, so use your project's real constraints to decide.

When Fixtures Are a Good Choice

  • The application is small to medium, and a handful of named records covers most scenarios.
  • You want zero extra dependencies and the simplest possible setup.
  • Your tests mostly read from a stable shared dataset.
  • Your team is comfortable with YAML and likes the speed of having data preloaded.

When FactoryBot Is a Better Fit

  • Tests need many variations of the same model, and traits would describe them well.
  • Models have many required attributes, and you want defaults handled in one place.
  • You want setup to be visible inside each test.
  • Your team already knows FactoryBot, or you use RSpec and the community conventions around it.

Weighing Project Size, Team Preferences, Complexity, and Performance

  • Project size. Small apps can run happily on fixtures. Larger apps often accumulate many states and combinations, where traits scale more gracefully than a growing YAML file.
  • Team preferences. A strategy your team understands and applies consistently beats a theoretically better one applied inconsistently.
  • Test complexity. If most tests need slightly different data, factories fit well. If most tests need the same stable data, fixtures fit well.
  • Performance. Measure before deciding. Use build and build_stubbed wisely with factories, keep fixtures small, and profile with bin/rails test --profile.

A practical way to decide is to start with the Rails default (fixtures), and introduce FactoryBot only when you feel real pain: variations that are awkward in YAML, or tests that need too much setup. If you already use FactoryBot and your suite is healthy, there is no reason to switch.


Conclusion

Fixtures and FactoryBot are two answers to the same question: how do we give our tests the data they need? Fixtures are built into Rails, load once, and give you a shared, readable dataset, but they bypass validations, hide details in YAML, and can couple tests together. FactoryBot is an extra gem that creates data on demand, runs through your models, and makes variations easy, but it can slow a suite when create is overused and can become complicated when factories grow.

The best test data, whichever tool produces it, makes tests clear, reliable, and maintainable. Keep records minimal, make important attributes visible in the test, avoid shared mutable state, and use the cheapest strategy that keeps the test honest.

Pick a consistent strategy based on your application's needs, write down the convention, and revisit it when your suite tells you it is hurting. A clear, consistent approach will serve you far better than winning the FactoryBot vs fixtures debate.

Jean Emmanuel Cadet
Written by Jean Emmanuel Cadet
Jean Emmanuel is a Full-Stack Software Engineer specializing in Ruby on Rails and the modern Rails ecosystem. He builds scalable, maintainable web applications using Rails, Hotwire (Turbo & Stimulus), PostgreSQL, and SQLite, with a focus on fast, dynamic user experiences. Through CodeCurious, he shares practical lessons, development insights, and real-world solutions for modern developers.

Code. Learn. Grow.

A friendly newsletter sharing dev tips, lessons, and wins from my journey.