When rails fixtures and namespaces collide
Testing helps Rails apps work properly and stops bugs. Fixtures are a useful testing tool. But fixtures can cause problems when models are namespaced.
Say your app has a regular
Vehicle model and a namespaced
Vehicles::Car model. By convention, you'd think to place the fixtures in
Doesn't work. Rails tries to load the fixtures from
Here is why: Rails uses both the fixture file name and path to find the right model.
vehicles.yml goes to
Vehicle based on the name. But so does
vehicles/cars.yml based on the path.
Don't just rename your model classes or namespaces to work around this.
vehicles_cars.yml (ie, it must not be in the
vechicles folder), and add these lines at the top of the file:
Now rails loads
Vehicles::Car, avoiding the collision.
Rails matches fixtures using name and path
Collisions happen when name of one class matches the path of another
Specify the model class explicitly rather than renaming your classes and namespaces
Explicit model classes remove guesswork. Fixtures load properly. Tests run cleanly. Careful fixture setup prevents headaches.