工厂女孩和has_one

Mik*_*ike 6 ruby-on-rails factory-bot

这是我的模特:

Class Audition
  belongs_to :video
end

Class Video
  has_one :audition
end
Run Code Online (Sandbox Code Playgroud)

和我的工厂:

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
Run Code Online (Sandbox Code Playgroud)

我怎么能创建一个有试镜的视频工厂,

我的意思是,能够:

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

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

我尝试了几件事情,但总是以堆叠水平太深或试镜为零结束.

你有好主意吗 ?

谢谢,迈克

tsd*_*own 7

如果是这种情况,我会将关联添加到其他工厂:

Factory.define :video do |v|
  v.filename                        {Sham.filename}
  v.video_url                       {Sham.url}
  v.audition                        {|v| v.association(:audition)}
end
Run Code Online (Sandbox Code Playgroud)

那你可以做

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

a = Factory(:audition) # An audition without a video, if that's possible?
Run Code Online (Sandbox Code Playgroud)

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

v = Factory(:video, :audition => Factory(:audition))
v = Factory(:video, :audition => nil)
Run Code Online (Sandbox Code Playgroud)

希望我所说的是有道理的,是真的哈哈.让我们知道您的身体情况如何.