百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
F

fixture_builder

> 编程语言
开源

基于固定装置场景代码的固定装置构建器

165 stars0 点赞1 次浏览
访问官网GitHub

工具介绍

基于固定装置场景代码的固定装置构建器

FixtureBuilder

[!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!

  • Speed: Leverage Rails' high-performance transactional tests and fixtures to avoid test suite slowdown as your app's number of tests grows, because creating and persisting data is slow.
  • Maintainability/Reuse/Abstraction: Use ordinary application code, including object mothers, to generate fixtures
  • Flexibility: You can always fall back to object mothers in tests if needed, or load a fixture and modify only an attribute or two without the overhead of creating an entire object dependency graph.
  • Consistency: Use the exact same fixture data in all environments: test, development, and demo/staging servers. Makes reproduction and acceptance testing of bugs/features faster and easier!
  • Simplicity: Avoid having to maintain and generate 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!

Requirements

  • Ruby 3.3+
  • Rails 8.0+

Installing

  1. Install:
  • Directly: gem install fixture_builder

  • Bundler:

    ruby
    # Gemfile
    group :development, :test do
      gem "fixture_builder"
    end
  1. Create a file which configures and declares your fixtures (see below for examples)
  2. Require the above file in your spec_helper.rb or test_helper.rb
  3. If you are using RSpec, ensure you have:
    • Set ENV["FIXTURES_PATH"] = "spec/fixtures" in config/application.rb so Rails database tasks use the same root-relative fixture directory.
    • Set config.fixture_paths = [Rails.root.join("spec/fixtures")] in spec/rails_helper.rb.
    • Set config.global_fixtures = :all if you don't want to specify fixtures in every spec file.
  4. You probably also want to use config.use_transactional_fixtures with RSpec, or use_transactional_tests with Rails tests.
  5. If you are using fixtures in Selenium-based Capybara/Cucumber specs that runs the tests and server in separate processes, you probably want to consider setting transactional fixtures to false, and instead using Database Cleaner with DatabaseCleaner.strategy = :truncation or DatabaseCleaner.strategy = :deletion.

Usage

  • When running tests/specs, fixtures will build/rebuild automatically as needed
  • rake spec:fixture_builder:build to force a build of fixtures
  • rake spec:fixture_builder:clean to delete marked FixtureBuilder output
  • rake 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)

Configuration Example

spec/rails_helper.rb or test/test_helper.rb:

ruby
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:

ruby
# 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
end

The 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:

yaml
# 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: 1

FixtureBuilder 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:

ruby
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.

ruby
fbuilder.name_model_with(User) do |record|
  [record['first_name'], record['last_name']].join('_')
end

For 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:

  • files_to_check: array of filenames that when changed cause fixtures to be rebuilt
  • fixture_builder_file: the pathname of the versioned SHA-256 manifest that binds configured source files to generated fixture YAML
  • record_name_fields: array of field names to use as a fixture's name prefix, it will use the first matching field it finds
  • skip_tables: array of table names to skip building fixtures
  • select_sql: sql string to use for select
  • delete_sql: sql string to use for deletes

By default these are set as:

  • files_to_check: %w{ db/schema.rb }
  • fixture_builder_file: Rails.root.join("tmp/fixture_builder.yml")
  • record_name_fields: %w{ unique_name display_name name title username login }
  • skip_tables: %w{ schema_migrations ar_internal_metadata }
  • select_sql: SELECT * FROM %s
  • delete_sql: DELETE FROM %s

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:

ruby
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.

Generated Fixture Ownership

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:

ruby
FixtureBuilder.configure do |fbuilder|
  fbuilder.fixture_directory = Rails.root.join("test/generated_fixtures")
  fbuilder.skip_tables += ["countries"]
end

For Minitest, register the generated root in test/test_helper.rb after rails/test_help and before declaring fixtures :all:

ruby
require "rails/test_help"

class ActiveSupport::TestCase
  self.fixture_paths += [Rails.root.join("test/generated_fixtures")]
  fixtures :all
end

For RSpec with rspec-rails 6.1 or newer, configure both roots in spec/rails_helper.rb:

ruby
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
end

Test-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:

bash
RAILS_ENV=development FIXTURES_PATH=test/generated_fixtures bin/rails db:fixtures:load

Use 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.

Sequence Collisions

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:

ruby
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

Tips

  • Don't use seeds.rb (just delete it). Instead, just use rake db:fixtures:load to get fixtures into dev.
  • If you want fixture data on a staging/demo environment, either run db:fixtures:load on that environment,

Issues· 13 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

Ruby

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月18日
分类编程语言
定价开源

> 相关工具

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言