Here's what I'm attempting to do. I have several objects but for simplicity's sake I'll keep it to two. The two objects have a many to one relationship. For instance:
class Foo < ActiveRecord::Base
has_many :bars
set_primary_key :BLAH
end
class Bar < ActiveRecord::Base
belongs_to :foo
end
Factory.define :foo
blahblahblah
end
Factory.define :bar do |t|
t.association :foo
end
Now what I want to know is if I create an instance of bar, (which will create an instance of foo), and the test finishes/fails/whatever the records remain in the database (by design). Now if I ran that same test again I would get a SQL error saying that primary key already exists in the db. What I want to know is how can I check to see if an instance of foo already exists in the db and if so skip trying to create it and continue with the creation of bar? Is that murky enough for you? :)
I know it may not be the most elegant solution but this is what I worked out and it seems to be doing what I need it to...
#defined in foo
def existing_foo(foo_id)
if(Foo.find_by_FOOID(foo_id) == NIL)
Factory(:foo, :foo_id => foo_id)
return :foo_id
end
Foo.find_by_FOOID(foo_id).FOOID
end
#defined in bar
Factory.define bar do |record|
record.sequence(:foo_id){|n|existing_foo("blah#{n}")}
end