ruby on rails - How to refer to the object I'm Fabricating inside my Fabricator? -


i'm using ruby 2.1.1p76 , rails 4.0.4 , fabrication gem.

is possible refer object being fabricated?

i have class foo , class bar. have fabricators each. problem each of class foo , bar contain field refers other class:

class foo < activerecord::base   has_many :bars   belongs_to :current_bar, class_name: "bar" end 

class bar < activerecord::base   belongs_to: :foo end 

it's bothersome have fabricate one, other , set reference first in specs:

let!( :foo ) { fabricate( :foo ) } let!( :bar ) { fabricate( :bar, foo: foo ) }  before( :each )   foo.update( current_bar: bar ) end  

i'd rather fabricate foo , have current_bar fabricated , referring foo i'm fabricating. i've read through fabrication gem documentation , can't find way possible. may overlooking it. know of way accomplish this?

for completeness -- fabricators:

fabricator( :foo )   current_bar nil end 

fabricator( :bar )   foo end 

yup. overlooked in documentation.


you can define them in fabricators block optionally receives object being fabricated , hash of transient attributes defined. works in fabricator, can define them when call fabricate , work you’d expect. callbacks stackable, meaning can declare multiple of same type in fabricator , not clobbered when inherit fabricator.

fabricator(:place)   before_validation { |place, transients| place.geolocate! }   after_create { |place, transients| fabricate(:restaurant, place: place) } end 

also, in case, needed use after_save callback. able set current_bar on foo object inside fabricator, once in spec, current_bar still nil. update method isn't available inside after_create (i'm new ruby i'm not sure why), available inside after_save. calling update got me going.

fabricator(:foo)    transient :current_bar_data    after_save { |foo, transients|     bar = fabricate( :bar, foo: foo, bar_data: transients[ :current_bar_data ] )     foo.update( current_bar: bar )   }    current_bar nil end 

now can fabricate foo complete current_bar specs:

let!( :some_foo ) { fabricate( :foo, current_bar_data: "some bar data" ) } 

Comments

Popular posts from this blog

PHPMotion implementation - URL based videos (Hosted on separate location) -

javascript - Using Windows Media Player as video fallback for video tag -

c# - Unity IoC Lifetime per HttpRequest for UserStore -