In a Rails app, how are YAML fixtures in test/fixtures loaded into the test database, and what does teams(:riverside) return inside a test?
answer
- one YAML file per table
- top-level keys are labels
- fixtures :all in test_helper.rb
- accessor finds the row by id
- unknown label raises StandardError
basics
~10 sEach test/fixtures/*.yml file holds labelled rows for one table; fixtures :all in test_helper.rb inserts them before the tests run, and teams(:riverside) returns the Team record with that label, loaded from the database.
solid answer
~40 sA fixture file such as `test/fixtures/teams.yml` maps to the `teams` table. Each top-level key, like `riverside:`, is a **label** for one row, and its nested keys are column values. The generated `test/test_helper.rb` calls `fixtures :all` inside `ActiveSupport::TestCase`, so before the first test Rails deletes the rows in every fixture table and inserts the YAML rows with plain SQL. That also defines an accessor per file: `teams(:riverside)` finds that row through `Team` and returns a real Active Record object, cached for the rest of the test. `teams(:riverside, :harbor_city)` returns an array, `teams` with no arguments returns every team fixture, and an unknown label raises `StandardError`. Because the rows are inserted directly, validations and callbacks do not run.
code
ruby · 9 linesclass TeamTest < ActiveSupport::TestCase
test "a fixture is a real record" do
riverside = teams(:riverside)
assert_equal "Riverside Rovers", riverside.name
assert_includes riverside.players, players(:alice)
assert_equal 2, teams(:riverside, :harbor_city).size
end
endgo deeper
Know where fixture files live, that labels name the rows, and that teams(:riverside) gives you a real record you can call methods on.
Explain the load sequence: delete, raw insert, foreign-key check, and why validations, callbacks and model defaults are skipped.
Keep a growing fixture set trustworthy: label conventions, accessor caching with :reload, and catching invalid rows that bypassed validations.
Decide what a shared fixture set should represent for the whole team, so tests do not quietly depend on rows added for someone else's feature.
## What a fixture file is A **fixture** is a row of sample data written in YAML. Rails keeps them in `test/fixtures/`, one file per table: ```yaml # test/fixtures/teams.yml riverside: name: Riverside Rovers founded_on: 1921-08-14 harbor_city: name: Harbor City founded_on: 1934-03-02 ``` - The file name gives the **fixture set** name and, by default, the table (`teams`) and model (`Team`). - Each top-level key (`riverside`, `harbor_city`) is a **label**: a name for humans that tests use to refer to the row. - The nested keys are column values. Columns you leave out get the database default, except the id and timestamps, which Rails fills. - `bin/rails generate model Team name:string` writes a starter `teams.yml` with two rows labelled `one` and `two`. ## How fixtures :all loads them The generated `test/test_helper.rb` contains: ```ruby module ActiveSupport class TestCase parallelize(workers: :number_of_processors) fixtures :all end end ``` `fixtures :all` globs every `.yml` file under the fixture paths (`test/fixtures/` by default, skipping `test/fixtures/files`). For the first test that runs, Rails then: 1. runs `DELETE FROM` on every fixture table; 2. inserts every fixture row with plain `INSERT` statements, inside one transaction, with referential integrity temporarily disabled; 3. checks all foreign keys, when `config.active_record.verify_foreign_keys_for_fixtures` is on (it is under `load_defaults` 7.0 and later); 4. resets primary-key sequences so later inserts do not collide. Because the rows go in as SQL, **validations, callbacks and model-level defaults do not run**. Timestamp columns (`created_at`, `updated_at`) are filled with the load time if you leave them out. ## The accessor methods For every fixture set, Rails defines a method named after the file: | Call | Returns | |---|---| | `teams(:riverside)` | the `Team` record labelled `riverside` | | `teams(:riverside, :harbor_city)` | an array of those two records | | `teams` | every record in `teams.yml` | | `teams(:nowhere)` | raises `StandardError` ("No fixture named 'nowhere' found for fixture set 'teams'") | | `fixture(:teams, :riverside)` | the same record, for set names that clash with a test method | - The accessor runs a `find` through the model, so you get a normal Active Record object with associations and methods. - The result is **cached for the current test**. If the test changes the row through another object, pass `:reload` (or `true`) as the last argument, or call `reload` on the record. - Fixtures in subfolders get underscored accessors: `test/fixtures/league/seasons.yml` becomes `league_seasons(:current)`. ## Selecting fewer fixtures `fixtures :all` is the default, but a test class can name sets explicitly: `fixtures :teams, :players`. When a fixture file's name does not match its model, `set_fixture_class` in the test class, or a `_fixture: model_class: Team` entry inside the YAML file, tells Rails which class to use. ## Common mistakes - **Expecting validations to guard fixtures.** A fixture can hold a team with a blank name; the model test that loads it is the first to notice. - **Assuming a fresh database per test.** The rows are loaded once and each test's changes are rolled back, which is why a test can delete `teams(:riverside)` and the next test still finds it. - **Hard-coding ids.** Rails generates stable ids from labels, so tests should use `teams(:riverside).id` rather than a literal number. ## Keeping a growing fixture set readable - **Name labels after the role the row plays**, not after sequence numbers: `relegated_team`, `injured_player` and `abandoned_match` explain themselves in a failure message, while `one` and `two` from the generator do not. - **Keep few rows per table.** Every row is loaded for every test run, and every extra row is a fact some test may start depending on. - **Avoid counting all rows.** `assert_equal 2, Team.count` breaks the day someone adds a fixture for a new feature; count a scope that the test controls instead. - **One story per label.** When a test needs a variation, change the record inside the test (`teams(:riverside).update!(...)`) rather than adding a near-duplicate row that other tests will start using.
- If one Rails test destroys teams(:riverside), why does the next test still find it?Transactional tests are on by default: fixtures are inserted once and every test runs inside a transaction that is rolled back in teardown. The destroy is undone before the next test starts, so the row is back without reloading the YAML.
- How do you use a fixture file whose name does not match its model, such as test/fixtures/clubs.yml for Team?Either call `set_fixture_class clubs: Team` in the test class, or add a `_fixture:` section with `model_class: Team` at the top of `clubs.yml`. The YAML form also works outside tests, for example when loading fixtures into the development database.
- Fixture rows are saved through the model, so validations reject invalid YAML.
- teams(:riverside) returns the raw hash of YAML values, not a record.
- An unknown fixture label makes the accessor return nil.
- Each fixture's id must be written by hand in the YAML file.
- fixtures :all reloads every YAML file before each test.