12 Jun 2014 By: Greg MolnarTweet
Fixtures are the officially supported way to handle test data and lately they are getting some attention finally. I guess I am not the only developer who started with FactoryGirl because there was more tutorials about it that time, and it seemed a really great way to handle test data as a junior ruby developer. As time went by, the projects I was working on grew and I realized that my test suite's speed issues are mostly related to my factories. So I decided to give a shot to Fixtures. It was a quite positive experience and fixtures made a huge impact on the speed of test runs. But enough of the story about me let's see how can you use fixtures with Rails.
Fixtures are stored in a yaml file but they are also processed with ERB before sent to the yaml parser, so we can use Ruby to make them dinamic. Let's use the good old blog example:
# posts.yml post_one: id: 1 title: First Post published_at: <%= 1.day.ago %> post_two: id: 1 title: Second Post published_at: <%= Time.now %>
You would also want to handle relations too with your test data and fortunately that's not an issue with fixtures. You can simply use the "label" to reference another fixture:
# users.yml greg: name: Greg email: ... # posts.yml post_one: title: First Post author: greg published_at: <%= 1.day.ago %>
As you see, there is a simple reference to the user model in the
posts.yml which will setup the relation.
You can also implement somewhat of an inheritence in your fixtures by using the
# posts.yml DEFAULTS: &DEFAULTS active: true tags: "foo, bar" post_one: title: First Post author: greg <<: *DEFAULTS post_two: title: Second Post author: greg <<: *DEFAULTS
This can be handy if your fixtures shares multiple attributes with the same values.
Brandon Hilkert also shared his 7 reason of switching to fixtures and Minitest, which is a great reading: 7 REASONS WHY I'M STICKING WITH MINITEST AND FIXTURES IN RAILS
I hope this little write up will make you to give a try to fixtures if you are not using them now.
I hate spam as much as you do, so I won't send you anything else than Ruby/Rails related updates occasionally, and of course you can unsubcribe anytime.