6

我正在使用 Ruby 2.1.1p76 和 Rails 4.0.4 以及Fabrication gem

是否可以参考当前正在制造的对象?

我有一个类 Foo 和一个类 Bar。我有每个制造商。我的问题是每个类 Foo 和 Bar 都包含一个引用另一个类的字段:

class Foo < ActiveRecord::Base
  has_many :bars
  belongs_to :current_bar, class_name: "Bar"
end

class Bar < ActiveRecord::Base
  belongs_to: :foo
end

必须先制造一个,然后再制造另一个,然后在我的规范中为第一个设置参考,这很麻烦:

let!( :foo ) { Fabricate( :foo ) }
let!( :bar ) { Fabricate( :bar, foo: foo ) }

before( :each ) do
  foo.update( current_bar: bar )
end 

我宁愿只制造一个 Foo 并制造它的 current_bar 并且已经指代我正在制造的 Foo 。我已经阅读了制造 gem 文档,但找不到任何可能的方法。我可能只是忽略了它。有谁知道实现这一目标的方法?

为了完整性——制造商:

Fabricator( :foo ) do
  current_bar nil
end

Fabricator( :bar ) do
  foo
end
4

1 回答 1

7

Yup. overlooked it in the documentation.


You can define them in your Fabricators as a block that optionally receives the object being fabricated and a hash of any transient attributes defined. As with anything that works in the Fabricator, you can also define them when you call Fabricate and they will work just like you’d expect. The callbacks are also stackable, meaning that you can declare multiple of the same type in a fabricator and they will not be clobbered when you inherit another fabricator.

Fabricator(:place) do
  before_validation { |place, transients| place.geolocate! }
  after_create { |place, transients| Fabricate(:restaurant, place: place) }
end

Also, in my case, I needed to use the after_save callback. I was able set the current_bar on my foo object inside the fabricator, but once in the spec, the current_bar was still nil. The update method isn't available inside after_create (I'm new to ruby so I'm not sure why), but it is available inside after_save. Calling update got me going.

Fabricator(:foo) do

  transient :current_bar_data

  after_save { |foo, transients|
    bar = Fabricate( :bar, foo: foo, bar_data: transients[ :current_bar_data ] )
    foo.update( current_bar: bar )
  }

  current_bar nil
end

Now I can fabricate a foo complete with current_bar for my specs:

let!( :some_foo ) { Fabricate( :foo, current_bar_data: "some bar data" ) }
于 2014-04-06T17:52:37.823 回答