gpt4 book ai didi

ruby-on-rails - FactoryGirl - 在一个循环中定义几个工厂

转载 作者:太空宇宙 更新时间:2023-11-03 17:54:04 25 4
gpt4 key购买 nike

我试图通过定义 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: Attribute already defined: attribute

最佳答案

当您遍历 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

关于ruby-on-rails - FactoryGirl - 在一个循环中定义几个工厂,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17909140/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com