我试图通过定义1个工厂而不是30个来节省一些时间。
为什么这不起作用?
(假设我们有一个名为:wanted_attributes的类方法)
require 'rubygems'
require 'faker'
models = %w[Model1 Model2]
models.each do |model|
factoryname = model.downcase + "_e"
FactoryGirl.define do
factory factoryname.to_sym, :class => model do
model.constantize.wanted_attributes.each do |attribute|
attribute Faker::Name.first_name
end
end
end
end
我收到了错误:
FactoryGirl :: AttributeDefinitionError:已定义的属性: 属性
答案 0 :(得分:4)
当您循环遍历wanted_attributes时,您始终会创建名为“attribute”的单个属性。您需要使用send方法来确保使用属性变量的值而不是名称'attribute':
require 'rubygems'
require 'faker'
models = %w[Model1 Model2]
models.each do |model|
factoryname = model.downcase + "_e"
FactoryGirl.define do
factory factoryname.to_sym, :class => model do
model.constantize.wanted_attributes.each do |attribute|
send(attribute.to_sym, Faker::Name.first_name) ##### Use send
end
end
end
end