指定构建未创建的FactoryGirl关联

时间:2014-07-28 20:22:59

标签: ruby-on-rails ruby-on-rails-4 rspec factory-bot

我有两个有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位置?

2 个答案:

答案 0 :(得分:0)

build_stubbedattributes_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
相关问题