Fixtures and serialized attributes in Ruby on Rails
If you've ever used the serialize method in an ActiveRecord model, you may have faced the problem of writing a fixture for that particular serialized field. The serialize method is quite handy if you need to store a complex object (like a Hash or an Array) in a database field, without having to create additional models and relationships between them. A good example could be store the preferences of a user in a hash:
This way you can set and get the preferences attribute of the user without having to worry much about it:
In order to do that, at the database table for the User class, among the other fields you'll need to add a text column for the preferences. After that, you can easily work with your model without too much of a hassle.
If you care to look at the rows of the model's table, you'll see that the serialized attribute is stored in YAML format:
Now, that if you need to add a fixture for your model that needs the preferences attribute to be set to a particular value? If you have to manually parse the value you want to put in there to be tested, it'll be a pain in the ass. Even if you have a script that converts certain values to YAML so you can copy and paste the script output to the fixture, it's not very comfortable. Hopefully, you have to remember that you can use some ERB magic in your fixtures :) So, here's the deal if you need to add something to the serializable attribute:
The to_yaml method converts the Hash into a YAML representation, and with inspect we convert that to a string. Using this technique, we can add whatever we want to a serialized field in our fixtures.