如何通过迭代在FactoryBot中创建多个记录



规范/工厂/组织_groups.rb

FactoryBot.define do
@organisation_groups = [{name: 'WWZY', uuid: '68a0c637'}, {name: 'WCC', uuid: '0a13362e'}, {name: 'ECW', uuid: 'fdcdb1b2'}, {name: 'ZPE', uuid: 'fdcdb1b8'}]
@organisation_groups.each do |group|
factory :organisation_group do
name group[:name]
uuid group[:uuid]
end
end
end

我试图使用FactoryBot创建多个记录,但问题是我收到了这个错误:

NoMethodError:
undefined method 'name' in 'organisation_group' factory
Did you mean? 'name { "WWZY" }'

user_spec.rb

describe '#organisation_group' do
before(:each) do
@organisation_groups = create(:organisation_group)
end
end

更新1

FactoryBot::DuplicateDefinitionError:
Factory already registered: organisation_group

这比我想象的要难!在几次失误之后,这就奏效了:

FactoryBot.define do
factory :organisation do
name { 'foo' }
uuid { '12ab56ef' }
end
end

使用调用

@organisation_groups = [
{name: 'WWZY', uuid: '68a0c637'}, 
{name: 'WCC', uuid: '0a13362e'}, 
{name: 'ECW', uuid: 'fdcdb1b2'}, 
{name: 'ZPE', uuid: 'fdcdb1b8'}
]
@organisation_list = @organisation_groups.map do |o| 
FactoryBot.create(:organisation, name: o[:name], uuid: o[:uuid])
end

它没有你想要的那么干净,但它能完成任务!

相关内容

  • 没有找到相关文章

最新更新