是否可以基于正在创建的实例创建属性?

时间:2019-08-08 01:04:44

标签: factory-bot

在FactoryBot 5中,我需要创建一个具有从属对象的工厂。需要使用对象的一些信息来创建依赖对象。

这确实可行,但是我不想抓住FactoryBot的胆量。

factory :thing do
  dependent { |instance|
    create(:dependent, tag: instance_variable_get('@instance').tag)
  }
end

当前,我正在使用after(:build)回调,但是即使传入了依赖项,它总是会改变它。

factory :thing do
  dependent

  after(:build) { |thing|
    dependent = thing.dependent
    dependent.update!(tag: thing.tag)
  }
end

这就是我期望在Rspec中发生的事情。

it 'should set the tag if dependent is not given' do
  thing = build(:thing)
  expect( thing.dependent.tag ).to eq thing.tag
end

it 'should not set the tag if a dependent is given' do
  dependent = create(:dependent, tag: "foo")
  thing = build(:thing, dependent: dependent)
  expect( thing.dependent.tag ).to eq "foo"
end

0 个答案:

没有答案