ruby - Is it possible to ask Factory Girl what associations a given factory has? -


factory girl incredibly useful functional testing, has 1 annoying property makes harder use in unit tests, don't want rely on test database. use factory.build create factory can pass around or assign activerecord.find call using flexmock:

require 'test_helper' require 'flexmock'  class somemixintest < activesupport::testcase   include flexmock::testcase    def setup     @foo = factory.build(:foo, :id => 123,         :bar => factory.build(:bar, :id => 456,             :baz => factory.build(:baz, :id => 789)         )     )      flexmock foo, :find => @foo   end    def test_find_by_reverse_id     assert_equal @foo, foo.find_by_reverse_id(321)   end end 

this pattern nice, since cares not presence of database, , runs faster if objects had persisted. however, bit annoying have build associated objects manually. if don't, associated objects are created in database build call, if had used create instead.

assert_equal [], foo.all foo = factory.build :foo  # build associations too, please assert_equal [], foo.all  # ma, no mocks! assert_equal [], bar.all  # <=== assertion failed assert_equal [], baz.all 

this non-intuitive least, , causes actual problem when i'm testing few classes need play nicely mixin. want able this:

  klasses_under_test = [foo, bar, baz]    def test_find_by_reverse_id     klasses_under_test.each |klass|       objects = (123..456).map |id|         factory.build klass.to_s.downcase.to_sym, :id => id       end        flexmock klass, :all => objects        objects.each |object|         assert_equal object, klass.find_by_reverse_id(object.id.to_s.reverse), "#{klass} #{object.id}"     end   end 

but has nasty side effect of creating 333 bars , 666 bazes ("baz" sound kind of demon's nickname, maybe that's fitting) in database, making test slower molasses flowing uphill in winter.

i'd create helper method this:

  def setup_mocks(klass)     klass_sym = klass.to_s.downcase.to_sym     objects = (123..456).map{|id|       associated_objects = hash[         factory.associations(klass_sym).map |association|           [ association, setup_mocks(association, 1) ]         end       ]        factory.build klass_sym, associated_objects     end      flexmock klass, :all => objects     objects   end 

so, factory.associations exist?

i've not tested this, looking @ source seems should work:

factorygirl.find(:factory_name).associations 

Comments

Popular posts from this blog

php - What is the difference between $_SERVER['PATH_INFO'] and $_SERVER['ORIG_PATH_INFO']? -

fortran - Function return type mismatch -

queue - mq_receive: message too long -