工厂女孩和has_one [英] Factory Girl and has_one

查看:73
本文介绍了工厂女孩和has_one的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的模特:

Class Audition
  belongs_to :video
end

Class Video
  has_one :audition
end

和我的工厂:

Factory.define :video do |v|
  v.filename  {Sham.filename}
  v.video_url {Sham.url}
end

Factory.define :audition do |a|
  a.video     {|a| a.association(:video)}
  a.label     {Sham.label}
end

我如何创建一个带有试奏的视频工厂,

How could I create a video factory that have an audition,

我的意思是,能够:

v = Factory.create(:video)
v.audition # I'd like this to be not nil !

因为我的视频上有一个观察者,试图从视频对象访问试听

Because I have an observer on my video that try to access the audition from the video object

我尝试了几件事,但是我总是以太深的堆栈级别或试听为零而结束.

I tried several things but I always end with a stack level too deep or audition nil.

你有个主意吗?

谢谢, 迈克

推荐答案

如果是这种情况,我会将关联添加到另一个工厂中:

If that's the case I would add the association into the other factory:

Factory.define :video do |v|
  v.filename                        {Sham.filename}
  v.video_url                       {Sham.url}
  v.audition                        {|v| v.association(:audition)}
end

那你就可以做

v = Factory(:video) # This will now have an audition
a = v.audition # This should not be nil

a = Factory(:audition) # An audition without a video, if that's possible?

在测试中创建工厂时,您还可以根据需要覆盖任何关联,即:

You can also override any association as needed when you create the factory in your tests, i.e:

v = Factory(:video, :audition => Factory(:audition))
v = Factory(:video, :audition => nil)

希望我所说的是有道理的,是真的.让我们知道你的生活吧.

Hope what I've said makes sense and is true lol. Let us know how you get on.

这篇关于工厂女孩和has_one的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆