I tried factroy_girl yesterday to work with rspec framework, It’s excellent way to support testing, however, the polymorphic association in factroy_girl almost defeated me.
The factory definition in my code is as:

Factory.define :item do |i|
    i.status 0
    i.related_with_id 1
    i.association :unit
end

Factory.define :study_record do |sr|
    sr.association :content, :factory => :item
    sr.add_attribute :interaction_id
    sr.add_attribute :finished_at
end

Then I did this:


    @item = Factory(:item)
    @study_record = Factory(:study_record)
    @item.study_records << @study_record

But actually, this does not work to associate @study_record with @item, the problem is that @study_record.content is totally a new instance of Item rather than @item. It seems that "<<" doesn't work in this case.
The right way to do so:


     @item = Factory(:item)
    @study_record = Factory(:study_record, :content => @item)

Polymorphic association works, and it’s better than the fixtures solution indeed.

Leave a Reply

(required)

(required)


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

© 2011 Refactoring Thoughts Suffusion theme by Sayontan Sinha
普人特福的博客cnzz&51la for wordpress,cnzz for wordpress,51la for wordpress