开发者

Factory girl: create an object with an association to an existing object

I'd like to create two objects that refer to another, single object that I've created in the before(:each) block

eg.

# in my factories.rb file..
factory :blah_1 do
  association :foo, :factory => :foo
end

...

# in my spec..

before(:each) do
  foo = Factory(:foo)
end

...

foo.blahs << Factory(:blah_1)
foo.blahs << Factory(:blah_1)
# some test on foo to make sure the right thing happened

When I run this spec it tries to create an instance of foo for both blah_1 and blah_2, failing because I don't allow a duplicate attribute.

I'd like to get both blah_1 and blah_2 to reference a single foo factory.

T开发者_开发知识库hanks in advance for your help :)


What I ended up doing that fixed me (please let me know if this is bad form!)..

# in my factories.rb..
factory :blah_1 do
  # attributes, no associations
end

# in my spec..
before(:each) do 
  @foo = Factory(:foo)
end

...

foo.blahs << Factory(:blah_1, :foo => @foo)
foo.blahs << Factory(:blah_2, :foo => @foo)

It seems pretty reasonable from my perspective..

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜