基于固定装置场景代码的固定装置构建器
[!NOTE] As of August 2026, FixtureBuilder is maintained by Grant Hutchins. Grant is preparing a 0.6 release with some long-needed fixes, coming shortly. Follow the maintainer backlog triage plan for current priorities and progress. Contributions are encouraged and warmly welcomed.
Based on the code from fixture_scenarios, by Chris Wanstrath. Allows you to build file fixtures from ordinary Active Record model code, including object mothers such as Factory Bot, to generate high-performance fixtures that can be shared across your tests and development environment.
The best of all worlds!
seeds.rb sample data set separately from your test fixture/factory data set,
or pick which of the myriad seeds helper gems to use. Just delete
seeds.rb and forget about it!Directly: gem install fixture_builder
Bundler:
# Gemfile
group :development, :test do
gem "fixture_builder"
endspec_helper.rb or test_helper.rbENV["FIXTURES_PATH"] = "spec/fixtures" in config/application.rb so Rails
database tasks use the same root-relative fixture directory.config.fixture_paths = [Rails.root.join("spec/fixtures")] in
spec/rails_helper.rb.config.global_fixtures = :all if you don't want to specify fixtures in every spec file.DatabaseCleaner.strategy = :truncation or DatabaseCleaner.strategy = :deletion.rake spec:fixture_builder:build to force a build of fixturesrake spec:fixture_builder:clean to delete marked FixtureBuilder outputrake spec:fixture_builder:rebuild to force a rebuild of fixtures (just a clean + build)rake db:fixtures:load to load built fixtures into your development environment (this is a standard Rails rake task)spec/rails_helper.rb or test/test_helper.rb:
require_relative 'support/fixture_builder'FixtureBuilder does not depend on Factory Bot. When using it as an object mother, set it up like the following:
# spec/support/fixture_builder.rb
FixtureBuilder.configure do |fbuilder|
# rebuild fixtures automatically when these files change:
fbuilder.files_to_check += Dir["spec/factories/*.rb", "spec/support/fixture_builder.rb"]
# now declare objects
fbuilder.factory do
david = FactoryBot.create(:user, unique_name: "david")
ipod = FactoryBot.create(:product, name: "iPod")
FactoryBot.create(:purchase, user: david, product: ipod)
end
endThe block passed to the factory method initiates the creation of the fixture files. Before yielding to the block, FixtureBuilder cleans out the test database completely. When the block finishes, it dumps the state of the database into fixtures, like this:
# users.yml
david:
created_at: 2010-09-18 17:21:23.926511 Z
unique_name: david
id: 1
# products.yml
i_pod:
name: iPod
id: 1
# purchases.yml
purchase_001:
product_id: 1
user_id: 1FixtureBuilder guesses about how to name fixtures based on a prioritized list of attribute names.
You can also hint at a name or manually name an object. Both of the following lines would
work to rename purchase_001 to davids_ipod:
fbuilder.name(:davids_ipod, FactoryBot.create(:purchase, user: david, product: ipod))
@davids_ipod = FactoryBot.create(:purchase, user: david, product: ipod)Another way to name fixtures is to use the name_model_with. To use it you create a block that returns how you want a certain model name based on the record field.
fbuilder.name_model_with(User) do |record|
[record['first_name'], record['last_name']].join('_')
endFor all User fixture {first_name: 'foo', last_name: 'bar'} it would generate foo_bar as the fixture name.
There are also additional configuration options that can be changed to override the defaults:
By default these are set as:
FixtureBuilder omits database-generated columns from snapshots because Rails fixtures cannot write them.
FixtureBuilder supports Ruby's two
reference by name
forms for the table placeholder. In %s, table is the named key and
s formats its value as a string. %{table} is the alternate named string
replacement and has no trailing s. FixtureBuilder passes the quoted table
name as the value in either form:
format("SELECT * FROM %s", table: '"users"') # => "SELECT * FROM \"users\""
format("DELETE FROM %{table}", table: '"users"') # => "DELETE FROM \"users\""Positional %s placeholders were deprecated in FixtureBuilder 0.5.0 and are
rejected in 0.6. Assigning select_sql or delete_sql is deprecated but remains
supported throughout 0.6. The setters are planned for removal in 0.7 unless users
report using them.
FixtureBuilder rebuilds fixtures when configured source files or generated fixture YAML differ from the manifest. This detects stale ignored artifacts left by CI cache restores, local branch changes, or pulls. Invalid or older manifest formats rebuild automatically; malformed YAML raises an error instead of being silently replaced.
FixtureBuilder supports parallel testing frameworks by coordinating fixture generation across threads and processes, so only one worker rebuilds a stale snapshot while the others wait and reuse the completed result. A failed build leaves no valid manifest, so a waiter or later run retries. Only the manifest is replaced atomically after successful fixture generation; the fixture set itself is not published atomically.
Every generated YAML file starts with
# Generated by fixture_builder. Do not edit.. FixtureBuilder uses that exact first
line to identify its output. During a rebuild it removes marked files that are no
longer produced, including fixtures for dropped or newly skipped tables. The explicit
spec:fixture_builder:clean task likewise removes only marked YAML files. Unmarked
files are preserved when stale.
When a current output path contains an unmarked file, FixtureBuilder warns before replacing it and continues the build. A marked file remains generated output even if its YAML was edited, so a later build may overwrite or delete it. Existing version 1 manifests without marker adoption rebuild once and migrate quietly. Missing, invalid, or already-adopted manifests do not suppress collision warnings.
The default output directory remains the Rails fixture directory. To keep generated
and hand-authored fixtures separate, configure a sibling directory and register both
fixture roots with your test framework. Do not generate the same fixture-set name in
both roots. For example, if countries.yml is hand-authored, skip that table so an
empty generated file does not duplicate it:
FixtureBuilder.configure do |fbuilder|
fbuilder.fixture_directory = Rails.root.join("test/generated_fixtures")
fbuilder.skip_tables += ["countries"]
endFor Minitest, register the generated root in test/test_helper.rb after
rails/test_help and before declaring fixtures :all:
require "rails/test_help"
class ActiveSupport::TestCase
self.fixture_paths += [Rails.root.join("test/generated_fixtures")]
fixtures :all
endFor RSpec with rspec-rails 6.1 or newer, configure both roots in
spec/rails_helper.rb:
RSpec.configure do |config|
config.fixture_paths = [
Rails.root.join("spec/fixtures"),
Rails.root.join("spec/generated_fixtures")
]
config.global_fixtures = :all # Optional existing RSpec behavior
endTest-loader registration does not configure Rails database tasks. FIXTURES_PATH is
one root-relative directory, not a list. To load only generated fixtures in
development, run:
RAILS_ENV=development FIXTURES_PATH=test/generated_fixtures bin/rails db:fixtures:loadUse spec/generated_fixtures instead for the RSpec example. An explicit
fixture_directory override also does not retarget spec:fixture_builder:clean;
set FIXTURES_PATH consistently when cleaning or rebuilding. Explicit clean removes the
manifest, so the next build has no manifest-based migration suppression. Marker
migration does not remove historical unmarked duplicates; inspect or move those
manually.
One problem with generating your fixtures is that sequences can collide. When the fixtures are generated only as needed, sometimes the process that generates the fixtures will be different than the process that runs the tests. This results in collisions when you still use factories in your tests.
One solution is to explicitly reset the database primary key sequence through Active Record.
You could call this method before you run your factories in the fixture_builder.rb block:
def reset_pk_sequences
puts 'Resetting Primary Key sequences'
ActiveRecord::Base.connection.tables.each do |t|
ActiveRecord::Base.connection.reset_pk_sequence!(t)
end
end
seeds.rb (just delete it). Instead, just use rake db:fixtures:load to get fixtures into dev.db:fixtures:load on that environment,暂无开放 Issues,或尚未同步最近议题。