Fixtures and factories help you create test data easily. They make testing your Rails app faster and more reliable.
When you want to test your Rails models with sample data.
When you need consistent data for automated tests.
When you want to avoid writing repetitive setup code in tests.
When you want to simulate real-world data scenarios in tests.
Syntax
Ruby on Rails
# Fixture example (YAML file)
users:
alice:
name: Alice
email: alice@example.com
# Factory example (using FactoryBot)
FactoryBot.define do
factory :user do
name { "Alice" }
email { "alice@example.com" }
end
end
Fixtures are static YAML files loaded before tests run.
Factories use Ruby code to build data dynamically.
Examples
Fixtures are accessed by name, factories create new objects each time.
Ruby on Rails
# Using fixture in test
users(:alice)
# Using factory in test
create(:user)
Traits let you customize factories for different test cases.
Ruby on Rails
# Factory with traits
FactoryBot.define do
factory :user do
name { "Alice" }
email { "alice@example.com" }
trait :admin do
admin { true }
end
end
end
# Usage
create(:user, :admin)
Sample Program
This test file shows how to use both fixture and factory to test a User model.
Ruby on Rails
# test/models/user_test.rb
require "test_helper"class UserTest < ActiveSupport::TestCase
test "fixture user has correct name" do
user = users(:alice)
assert_equal "Alice", user.name
end
test "factory user is valid" do
user = FactoryBot.create(:user)
assert user.valid?
end
end
OutputSuccess
Important Notes
Fixtures load data once and reuse it, so changes in tests can affect others.
Factories create fresh data each time, avoiding test interference.
Use factories when you need flexible or complex test data.
Summary
Fixtures and factories help create test data in Rails.
Fixtures use YAML files; factories use Ruby code.
Factories offer more flexibility and avoid shared state issues.
Practice
(1/5)
1. What is the main difference between fixtures and factories in Rails testing?
easy
A. Fixtures use static YAML files, while factories generate data dynamically with Ruby code.
B. Fixtures are faster to write than factories.
C. Factories require no setup, but fixtures need database cleaning.
D. Factories store data in YAML files, fixtures use Ruby code.
Solution
Step 1: Understand fixtures data source
Fixtures load test data from static YAML files before tests run.
Step 2: Understand factories data generation
Factories create test data dynamically using Ruby code during test execution.
Final Answer:
Fixtures use static YAML files, while factories generate data dynamically with Ruby code. -> Option A