Data Association with FactoryGirl

If you ever work with Rails and TDD, you may hear Factory girl: a great data mock gem to replace fixture. But sometime when your modal have some association with other modals, and that model have other associations, try to write a factory with callback (after build/create) become so hard. But thanks to thoughtbot, factory girl have data association build-in. You can read this post.

1
2
3
4
# If the factory name is the same as the association name, it's simple
factory :post do
author
end

If your can FactoryGirl.create :post, that will create a post and a author associate to that. So in your rspec test, it’s easy to use them

1
2
let(:post) {FactoryGirl.create(:post)}
let(:author) {post.author}


What’s more? I found out it work with mongoid embed documuntation too.

For example, a playlist embed a list of videos, you can set this association the same way as relational database.

1
2
3
4
5
6
7
8
9
factory :video do
title 'my lovely video 1'
url 'http://www.youtube.com/yiwbeyfa56'
playlist
end
factory :playlist do
title 'my playlist 1'
end

And FactoryGirl.create(:video) will create a playlist embed with one videos, etc

1
2
3
4
5
6
playlist = {
title: 'my playlist 1',
[
{ title : 'my lovely video 1',
url : 'http://www.youtube.com/yiwbeyfa56'}
]}