Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing child attributes from parent Factory Girl factories

I'm implementing Factory Girl as a replacement for fixtures in my Rails app. I have several tables that I'm trying to represent using associations. However, to throw a kink into the loop, beyond just defining the associations, I also need to access attributes of the child factories from the parent.

Below is an example of what I'm trying to do:

  • Factory :foo_bar is associated to Factory :foo, which is associated to Factory :bar
  • From :foo_bar, I'm trying to access attributes of both :foo and :bar

Here are the samples:

Factory.define :bar do |e|
  e.name          "Bar"
end

Factory.define :foo do |e|
  e.bar         {|b| b.association(:bar)}
end

Factory.define :foo_bar do |b|
  f = b.association(:foo)
  b.foo_id      foo.id
  b.bar_id      foo.bar_id
end

I've gone through a number of tutorials and other questions and haven't seen any examples of how to do this. Any ideas, or other ways of getting the same result?

Thanks!


EDIT

Based on a couple of the questions, here are some clarifications that I should have included originally...

:foo_bar is not a join table, but a model with other attributes of its own.

This is what I'm actually trying to accomplish:

  • have :foo_bar create an associated Factory
  • then have that associated Factory create it's associated Factory
  • (this is the element I'm struggling with) have :foo_bar access an attribute from the bottom level Factory

So, if :foo_bar > :foo > :bar then from :foo_bar, I'm trying to get at :bar's ID.

like image 480
shedd Avatar asked Oct 14 '22 00:10

shedd


1 Answers

I'm using an after_build hook to handle situations like this:

Factory.define :foo do |f|
  f.name "Foo"
  f.association :foo
  f.after_build do |obj|
    obj.foo_bar = obj.foo.bar
  end
end
like image 110
Jon Wood Avatar answered Oct 18 '22 04:10

Jon Wood