我有两个有has_one
关系的模型:
class Entity < ActiveRecord::Base
has_one :location, as: :locatable, dependent: :destroy
accepts_nested_attributes_for :location, allow_destroy: true
...
end
class Location < ActiveRecord::Base
belongs_to :locatable, polymorphic: true
...
end
我的entity
工厂:
FactoryGirl.define do
factory :entity do
association :location
...
end
end
当我想要build
实体时,FactoryGirl会创建位置:
> e = FactoryGirl.build(:entity)
SQL (0.4ms) INSERT INTO `locations` (`address`, `created_at`, `updated_at`) VALUES ('New York, NY, US', '2014-07-28 19:04:10', '2014-07-28 19:04:10')
=> #<Entity id: nil, name: "Foobar", ..., created_at: nil, updated_at: nil>
除了:
before(:each) do
@entity = Factory.build(:entity)
@location = Factory.build(:location, :entity => @entity)
end
有没有办法在构建实体时指示FactoryGirl build
位置,并在创建实体时指示create
位置?
答案 0 :(得分:0)
build_stubbed
或attributes_for
会让您想要。尝试:
before(:each) do
@entity = Factory.attributes_for(:entity)
@location = Factory.build(:location, :entity => @entity)
end
答案 1 :(得分:0)
这是对工厂的一个简单改变:
FactoryGirl.define do
factory :entity do
association :location, strategy: :build
...
end
end