Consider two models:
class User < ActiveRecord::Base
has_one :book
after_create :create_book
end
class Book < ActiveRecord::Base
belongs_to :user
validate_uniqueness :user_id
end
Each user can have and can only have one book. Then I have two Factory defined in my specs:
factory :user do
end
factory book do
user
end
Then here's the question, when I am writing test for Book
, I'd like to create a record book1
(let's call it) for Book
, when I use FactoryGirl.create(:book)
. It will create an instance of Book
and then tries to create the association defined user
. After creating the user, the after_create
is trigger, and book2
is created for user
. Then it tries to bind book1
with user
and is blocked by the uniqueness association.
Now I am using book = FactoryGirl.create(:user).book
. Is this the best/right way to do that? I think it's note so intuitive, as I am testing Book
, I think it would be the best to have book = FactoryGirl.create(:book)
Thanks a lot.
Aucun commentaire:
Enregistrer un commentaire