0
0
Ruby on Railsframework~5 mins

Fixture and factory usage in Ruby on Rails

Choose your learning style9 modes available
Introduction

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.