Because Rails inserts YAML fixtures with raw SQL, which model behaviour do the rows skip, and how do ERB, DEFAULTS and enum labels help keep them valid?
answer
- no validations, no callbacks
- model attribute defaults ignored
- enum labels are translated
- DEFAULTS and _fixture ignore
- ERB runs once, at load time
basics
~20 sFixture rows skip validations, callbacks and model-level attribute defaults, so they hold exactly what the YAML says; enum labels are translated, DEFAULTS anchors share values, and ERB computes values once at load time, so a validity test over all fixtures catches drift.
solid answer
~40 sRails builds INSERT statements straight from the YAML, so nothing on the model's save path runs: no validations, no `before_save` or `normalizes`, no counter-cache updates, and no defaults from `attribute :x, default:`; only database defaults apply. Rails still helps in three ways. Enum labels such as `status: scheduled` are mapped to their stored values, missing timestamps are filled, and `$LABEL` is interpolated. To share columns I use a YAML anchor under a `DEFAULTS` key, which Rails never inserts, or list a base row under `_fixture: ignore:`. ERB is evaluated when the file is loaded, so `<%= 2.days.from_now %>` is fixed at load time for the whole cached run. Because nothing validates the rows, a test that loops over each fixture set and asserts `valid?` catches rows that drift from the model.
code
ruby · 8 linesclass FixtureValidityTest < ActiveSupport::TestCase
test "every team, player and match fixture is valid" do
[teams, players, matches].flatten.each do |record|
assert record.valid?,
"#{record.class} #{record.id}: #{record.errors.full_messages.to_sentence}"
end
end
endgo deeper
Know that fixture rows skip validations and callbacks, and that enum labels like scheduled can be written as words.
Explain what the raw insert ignores, including normalizes and attribute defaults, and how DEFAULTS, _fixture ignore and ERB shape the files.
Catch fixture drift with a validity test, avoid load-time ERB clocks, and keep derived columns such as counter caches consistent by hand.
Decide how strictly fixture data must match model rules as the domain evolves, and what automated checks enforce that across teams.
## Rows go in as SQL When Rails loads fixtures it turns each YAML row into a hash, applies a few fixture-specific rules, and sends plain `INSERT` statements. The model is used only to **look up metadata**: the table name, the primary key, the timestamp columns, enums and associations. It never instantiates a record or calls `save`. That means these **do not run** for fixture rows: - validations, so a blank `name` or a duplicate `email` is inserted happily; - callbacks such as `before_validation`, `before_save` and `after_create`; - `normalizes` declarations, so an email written in capitals stays in capitals; - defaults declared with the Attributes API (`attribute :rating, default: 1000`); only defaults in the database schema apply; - counter caches, so a `players_count` column holds whatever the YAML says, or its schema default. ## What Rails does translate | YAML you write | What gets inserted | |---|---| | `status: scheduled` for `enum :status, { scheduled: 0, played: 1 }` | `0` | | no `created_at` / `updated_at` | the load time | | `email: [email protected]` on `alice` | `[email protected]` | | `team: riverside` | `team_id` from the label's hash | | no `id` | an id from the label's hash | Enum translation uses the model's enum mapping, so the YAML stays readable and survives a change of stored values. ## Sharing values: DEFAULTS and _fixture YAML anchors avoid repeating columns: ```yaml DEFAULTS: &DEFAULTS status: scheduled season: 2026 opening_day: <<: *DEFAULTS home_team: riverside away_team: harbor_city ``` - A row labelled `DEFAULTS` is **never inserted**. - For a base row with another name, list it under a `_fixture:` section: `_fixture: { ignore: [base] }`. The same section can set `model_class:` when the file name does not match the model. ## ERB: computed once Fixture files are rendered as ERB before the YAML is parsed: - loops can generate rows (`<% 1.upto(20) do |n| %>`); - helpers from a module included into `ActiveRecord::FixtureSet.context_class` are available in every file; - `ActiveRecord::FixtureSet.identify(:alice)` can be called for hand-written join rows. The trap is **time**. With transactional tests the fixtures load once per run, or once per parallel worker, so `kickoff_at: <%= 2.days.from_now %>` is frozen at load time. A test that travels in time does not move it. A suite that runs past midnight can also flip a "today" comparison. Prefer fixed dates in fixtures and compute relative times inside the test. ## Keeping fixtures honest 1. Add a model test that iterates every row of a fixture set (`teams.each { |t| assert t.valid?, t.errors.full_messages.to_sentence }`). 2. Set derived columns such as counter caches explicitly in the YAML, matching the rows that reference them. 3. Write normalised values directly, because no normaliser will fix them. 4. Keep ERB for structure and identifiers, not for "now". ## Generating volume and sharing helpers ERB is most useful for **shape**, not values: ```erb <% 1.upto(18) do |n| %> reserve_<%= n %>: name: Reserve <%= n %> team: harbor_city position: midfielder <% end %> ``` - This produces eighteen labelled players for a squad-size rule without eighteen hand-written blocks. - Helper methods defined inside one fixture file are not visible in another. Shared helpers belong in a module included into `ActiveRecord::FixtureSet.context_class` from `test_helper.rb`. - The rendering context also offers `binary(path)` for loading a file into a binary column.
- Why does a Rails fixture with kickoff_at: <%= 1.day.from_now %> make a time-travel test fail?ERB is evaluated when the fixture file is loaded, and with transactional tests that happens once per run or per worker. The value is a fixed timestamp by the time the test moves the clock, so it no longer sits one day after the test's 'now'. Use a fixed date in the YAML and travel relative to it, or set the time inside the test.
- A Rails fixture row stores an email in capitals even though the model has normalizes :email. Why?`normalizes` runs when attributes are assigned through the model. Fixtures never instantiate the model, they insert the YAML values directly, so the stored value is exactly what the file says. Write the normalised form in the YAML.
- Fixtures are created through the model, so before_save callbacks run.
- attribute :rating, default: 1000 fills the column for fixture rows.
- Enum columns in fixtures must hold the stored integer values.
- ERB in a fixture is re-evaluated before every test.
- A row labelled DEFAULTS is inserted like any other fixture.