The syntactic sugar of factories with the speed of fixtures.
FixtureBot lets you define your test data in a Ruby DSL and compiles it into standard Rails fixture YAML files. The generated YAML is deterministic and should be checked into git, just like a lockfile. Your tests never see FixtureBot at runtime; Rails just loads the YAML fixtures as usual.
Features:
- Ruby DSL for defining records, associations, and join tables
- Generators for filling in required columns (like email) across all records
- Stable IDs so foreign keys are consistent and diffs are clean across runs
- UUID support for tables with UUID primary keys
- Polymorphic associations with automatic type column resolution
- Schema auto-detection from your Rails database (no manual column lists)
- Auto-generates before your test suite runs (RSpec and Minitest)
More background at BeautifulRuby.com.
# spec/fixtures.rbFixtureBot.definedo# Generators fill in required columns so you don't have to repeat yourself.# |fixture| gives you the fixture key; bare methods give column values.user.email{ |fixture| "#{fixture.key}@example.com"}user:braddoname"Brad"email"brad@example.com"# overrides the generatorenduser:alicedoname"Alice"# email filled in by generator: "alice@example.com"enduser:deactivateddoname"Ghost"emailnil# explicit nil, generator skipped, email set to nullendpost:hello_worlddotitle"Hello World"body"Welcome to the blog!"author:brad# sets author_id to brad's stable IDtags:ruby,:rails# creates rows in posts_tagsendtag.name{ |fixture| fixture.key.to_s.capitalize}tag:ruby# name: "Ruby"tag:rails# name: "Rails"endThis generates YAML files like users.yml, posts.yml, tags.yml, and posts_tags.yml in your fixtures directory. Use them in tests like any other fixture:
# RSpecRSpec.describePost,type: :modeldofixtures:allit"belongs to an author"dopost=posts(:hello_world)expect(post.author).toeq(users(:brad))endend# MinitestclassPostTest < ActiveSupport::TestCasedeftest_belongs_to_authorpost=posts(:hello_world)assert_equalusers(:brad),post.authorendendAdd to your Gemfile:
gem"fixturebot-rails"The easiest way to get started:
rails generate fixturebot:installThis creates spec/fixtures.rb (RSpec) or test/fixtures.rb (Minitest) with a skeleton DSL file and adds the appropriate require to your test helper.
Add to spec/rails_helper.rb:
require"fixturebot/rspec"Create spec/fixtures.rb with your fixture definitions.
Fixtures are auto-generated before each suite run, no rake task needed.
Add to test/test_helper.rb:
require"fixturebot/minitest"Create test/fixtures.rb with your fixture definitions.
Fixtures are auto-generated when the helper is loaded, no rake task needed.
A fixturebot:compile rake task is also available if you prefer manual control:
bundle exec rake fixturebot:compileFixtureBot auto-detects your fixtures file (test/fixtures.rb or spec/fixtures.rb) and derives the output directory by stripping .rb (e.g. spec/fixtures.rb writes to spec/fixtures/). To override:
# config/application.rb or config/environments/test.rbconfig.fixturebot.fixtures_file="test/my_fixtures.rb"config.fixturebot.output_dir="test/fixtures"Define named records with literal column values:
FixtureBot.definedouser:braddoname"Brad"email"brad@example.com"endendRecords without a block get an auto-generated ID and any generator defaults:
FixtureBot.definedouser.email{ |fixture| "#{fixture.key}@example.com"}user:alice# => { id: <stable_id>, email: "alice@example.com" }endGenerators set default column values. They run for each record that doesn't explicitly set that column. Generators are never created implicitly; columns without a value or generator are omitted from the YAML output (Rails uses the database column default).
FixtureBot.definedouser.email{ |fixture| "#{fixture.key}@example.com"}endThe generator block receives a fixture object with a key method (the record's symbol name). Bare methods inside the block refer to column values set on the record:
FixtureBot.definedouser.display_name{ |fixture| "#{fixture.key} (#{email})"}endWhen a generator covers all the columns you need, records don't need a block at all:
FixtureBot.definedotag.name{ |fixture| fixture.key.to_s.capitalize}tag:ruby# name: "Ruby"tag:rails# name: "Rails"tag:testing# name: "Testing"endA literal value shadows the generator. An explicit nil also shadows it:
FixtureBot.definedouser.email{ |fixture| "#{fixture.key}@example.com"}user:braddoname"Brad"email"brad@hey.com"# literal, skips the generatorenduser:alicedoname"Alice"# no email set, generator produces "alice@example.com"enduser:deactivateddoname"Ghost"emailnil# explicit nil, skips the generator, sets email to nullendendReference other records by name for belongs_to:
FixtureBot.definedopost:hello_worlddotitle"Hello World"author:brad# sets author_id to brad's stable IDendendFor polymorphic belongs_to, reference the target using its table helper to set both _id and _type columns:
FixtureBot.definedopost:hellodotitle"Hello"endcomment:nicedobody"Nice post"endvote:upvote_postdovotablepost(:hello)# sets votable_id and votable_type: "Post"endvote:upvote_commentdovotablecomment(:nice)# sets votable_id and votable_type: "Comment"endendIn the manual schema, declare polymorphic associations with polymorphic:
FixtureBot::Schema.definedotable:posts,singular: :post,columns: [:title]table:comments,singular: :comment,columns: [:body]table:votes,singular: :vote,columns: [:votable_id,:votable_type,:voter_id]dopolymorphic:votablebelongs_to:voter,table: :usersendendIn Rails, polymorphic associations are auto-detected from _id/_type column pairs that don't have a foreign key constraint.
Reference multiple records for join table associations:
FixtureBot.definedopost:hello_worlddotitle"Hello World"tags:ruby,:rails# creates rows in posts_tagsendendBy default, FixtureBot generates stable IDs deterministically from the table and record name. You can override this with an explicit value:
FixtureBot.definedouser:admindoid42name"Admin"endpost:hellodotitle"Hello"author:admin# author_id resolves to 42endendTables with UUID primary keys work automatically in Rails (detected from the column type). In the manual schema, pass key: FixtureBot::Key::Uuid:
FixtureBot::Schema.definedotable:projects,singular: :project,columns: [:name],key: FixtureBot::Key::UuidendFixtureBot generates deterministic UUID v5 values, so the output is stable across runs.
You can also provide your own key strategy — any object (or module) that responds to generate(table_name, record_name). For example, Stripe-style prefixed IDs:
modulePrefixedKeymodule_functiondefgenerate(table_name,record_name)hash=Zlib.crc32("#{table_name}:#{record_name}").to_s(36)"#{table_name.to_s.chomp('s')}_#{hash}"endendFixtureBot::Schema.definedotable:customers,singular: :customer,columns: [:name],key: PrefixedKey# => customer_id: "customer_1a2b3c"endIf your table uses a column other than id as the primary key:
FixtureBot::Schema.definedotable:users,singular: :user,columns: [:name],primary_key: :uidendIn Rails, this is auto-detected from the database.
For larger apps, split fixtures across multiple files using FixtureBot.require:
# spec/fixtures.rbFixtureBot.require"spec/fixtures/**/*.rb"FixtureBot.definedouser.email{ |fixture| "#{fixture.key}@example.com"}end# spec/fixtures/users.rbFixtureBot.definedouser:braddoname"Brad"endend# spec/fixtures/posts.rbFixtureBot.definedopost:hellodotitle"Hello"author:bradendendEach file calls FixtureBot.define with its own block. Files are loaded in alphabetical order. References across files work because everything is resolved after all files are loaded.
By default, the block is evaluated implicitly. Table methods like user and post are available directly:
FixtureBot.definedouser:braddoname"Brad"endendIf you prefer an explicit receiver (useful for editor autocompletion or clarity in large files), pass a block argument:
FixtureBot.definedo |t|
t.user:braddoname"Brad"endendBoth styles are equivalent. Record blocks (the inner do...end) are always implicit.
FixtureBot reads your database schema automatically in Rails. Outside of Rails, you can define it by hand:
FixtureBot::Schema.definedotable:users,singular: :user,columns: [:name,:email]table:posts,singular: :post,columns: [:title,:body,:author_id]dobelongs_to:author,table: :usersendtable:tags,singular: :tag,columns: [:name]join_table:posts_tags,:posts,:tagsendFixtureBot provides build, create, attributes_for, and related methods that mirror FactoryBot's API. The key difference is that you pass both a table name and a fixture name instead of just a factory name:
# FactoryBot # FixtureBotbuild(:user)# build(:user, :brad)create(:user)# create(:user, :brad)build(:user,name: "X")# build(:user, :brad, name: "X")attributes_for(:user)# attributes_for(:user, :brad)build_list(:user,3)# build_list(:user, :brad, :alice, :bob)create_list(:user,3)# create_list(:user, :brad, :alice, :bob)build_pair(:user)# build_pair(:user, :brad, :alice)create_pair(:user)# create_pair(:user, :brad, :alice)build_stubbed(:user)# build_stubbed(:user, :brad)| Method | Behavior |
|---|---|
build(:user, :brad, **attrs) | Duplicates the fixture, applies overrides. Returns unpersisted. |
create(:user, :brad, **attrs) | Without overrides: returns the fixture (already persisted). With overrides: build + save!. |
build_stubbed(:user, :brad, **attrs) | Like build but retains id. Looks persisted without touching DB. |
attributes_for(:user, :brad, **attrs) | Returns attributes hash, strips id/created_at/updated_at. |
build_list(:user, :brad, :alice, **attrs) | Maps each name through build. |
create_list(:user, :brad, :alice, **attrs) | Maps each name through create. |
build_pair(:user, :brad, :alice, **attrs) | Alias for build_list with 2 names. |
create_pair(:user, :brad, :alice, **attrs) | Alias for create_list with 2 names. |
build_stubbed_list(:user, :brad, :alice, **attrs) | Maps each name through build_stubbed. |
build_stubbed_pair(:user, :brad, :alice, **attrs) | Alias for build_stubbed_list with 2 names. |
These methods are automatically available in your tests when you require fixturebot/rspec or fixturebot/minitest. They call the standard Rails fixture accessors under the hood, so build(:user, :brad) is equivalent to users(:brad).dup.
Rails fixtures are YAML files that get loaded into the database once before your test suite runs. Each test wraps in a transaction and rolls back, so the data is always clean and tests are fast. This is the approach FixtureBot builds on.
The problem is writing YAML by hand. Foreign keys are magic strings (author: brad), there's no way to DRY up repeated columns, and large fixture files are hard to read. FixtureBot gives you a Ruby DSL that compiles down to the same YAML, so you keep the speed of fixtures without the pain of maintaining them.
FactoryBot creates records on the fly inside each test. You call create(:user) and it inserts a row. This makes tests self-contained and easy to read, but it's slow. Every test that needs data pays the cost of inserting records, and complex object graphs lead to cascading create calls.
FixtureBot borrows the DSL feel of FactoryBot (named records, associations by symbol, default generators) but compiles to fixtures instead of inserting at runtime. You get the ergonomics of factories with the speed of fixtures.
Oaken and FixtureBot share the same motivation: replace hand-written YAML fixtures with a Ruby DSL. They take very different approaches.
Oaken inserts records into the database at runtime using ActiveRecord::Base#create!. It also supports loading different seed files per test case (seed "cases/pagination"), which means your data set can vary across tests. This flexibility comes at a cost: you lose the "load once, wrap every test in a transaction" speed advantage that makes Rails fixtures fast. It's closer to factories in that regard, with more structure around organizing seed scripts.
FixtureBot is more opinionated. One fixture file, one data set, compiled to plain YAML and checked into git. At test time, FixtureBot is out of the picture entirely. Rails loads the YAML fixtures once and wraps each test in a transaction as usual. No runtime dependency, no per-test seeding, no seed file organization to manage.
| FixtureBot | Rails fixtures | FactoryBot | Oaken | |
|---|---|---|---|---|
| Define data in | Ruby DSL | YAML | Ruby DSL | Ruby scripts |
| Output | YAML files in git | YAML files in git | Database rows per test | Database rows at boot |
| Runtime dependency | None | None | Required per test | Required at boot |
| Data set | One set, loaded once | One set, loaded once | Built per test | Per-test via seed files |
| Speed | Fast (fixtures) | Fast (fixtures) | Slow (inserts per test) | Varies |
| Stable IDs | Deterministic | Deterministic | Database-assigned | Database-assigned |
After checking out the repo, run bin/setup to install dependencies. Then, run rake spec to run the tests. You can also run bin/console for an interactive prompt.
Try the playground without Rails:
bundle exec exe/fixturebot show ./playground/blog