views:

95

answers:

2

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.

A: 

Hard to tell how it should look without the model code?

but maybe something like this?

Factory.define :bar do |f|
    f.name "Bar"
    f.association :foo_bar  
end

Factory.define :foo do |f|
    f.name "Foo"
    f.association :foo_bar  
end

Factory.define :foo_bar do |f|
    f.association :foo
    f.association :bar      
end
house9
Thanks for the response. I think my example didn't clearly illustrate the full question. I'll revise it to be more clear, but what I'm actually trying to do is have :foo_bar create an associated Factory, and then have that associated Factory create it's associated Factory, but (and this is the element I'm struggling with) also have :foo_bar access an attribute from the bottom level Factory. So, :foo_bar > :foo > :bar and from :foo_bar, I'm trying to get at :bar's ID. Does that make more sense?
shedd