Rails fixtures vs factories for test data

9901
0

Fixtures and factories both create test data, but suit different needs. Fixtures load YAML files into the database before tests, providing fast, consistent data. I use fixtures for static reference data like countries or categories. Factories (via FactoryBot) build objects programmatically with attributes and associations. They're more flexible for test-specific scenarios and maintain referential integrity automatically. Factories support traits for variations and sequences for unique values. I prefer factories for most tests since they're more maintainable and explicit. Fixtures excel for large, static datasets. The key is consistency—mixing both approaches causes confusion. For React integration tests, I mock API responses with MSW instead of seeding data.