工厂女孩:创建一个与现有对象关联的对象

发布于 2024-11-27 16:10:11 字数 524 浏览 1 评论 0原文

我想创建两个对象来引用我在 before(:each) 块中创建的另一个单个对象,

例如。

# 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

当我运行此规范时,它尝试为 blah_1 和 blah_2 创建 foo 的实例,但失败了,因为我不允许重复的属性。

希望让 blah_1 和 blah_2 都引用一个 foo 工厂。

预先感谢您的帮助:)

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.

Thanks in advance for your help :)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

爱冒险 2024-12-04 16:10:11

我最终所做的事情解决了我的问题(请告诉我这是否是不好的形式!)..

# 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)

从我的角度来看,这似乎相当合理..

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..

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文