Written by Sean Behan on Sun Jun 17th 2012

Fixtures in Rails allow you to quickly and easily populate a database with sample data. They are great when testing your app and you need to test against a condition that will rely on a certain preexisting data point.

Fixtures are located in your RAILS_ROOT/test/fixtures/model.yml where model.yml is the model in question. A sample fixture *note: yml files require consistent indentation!

one:
  id: 1
  title: my sample fixture
  description: this is an example of a fixture
  created_at: <%= 2.days.from_now.to_s :db %>
You can load your fixture data like so
rake db:fixtures:load
This assumes that you have a schema migration already raked <code>rake db:migrate</code> and that the attributes in your fixtures map to the correct attributes in your schema. You'll get an error otherwise. You can also specify the environment when you run your rakes like so...
rake db:fixtures:load RAILS_ENV="production"
As you may have noticed, you can execute Ruby code in your fixtures if you place your code in the normal erb tags <%= %>. Furthermore, you have access to the Rails api, which gives you handy methods like 2.days.ago.to_s. When creating your fixtures you might be tempted to use <%= Time.now %> for you created_at, updated_at fields. Don't! Instead, use the rails api like so... <%= 1.month.from_now.to_s :db %> This stores the value in the same way that Rails handles time stamping your models. Otherwise, you might find parts of your application break when running tests against your fixtures because the data types do not correspond.

Tagged with..
#development #testing #Programming #Ruby on Rails

Just finishing up brewing up some fresh ground comments...