如何覆盖 factory_bot 的生成器?
How to override a the generator for factory_bot?
我刚刚将 factory_bot's model_generator 复制到我的文件中 #lib/generators/factory_bot/model/model_generator.rb
这将是我开始进行更改的基准。
我能够通过更改
来证明它正在读取我的文件
需要“generators/factory_bot”
要求“factory_bot_rails”
module FactoryBot
module Generators
class ModelGenerator < FactoryBot::Generators::Base
puts 'my file'
def factory_definition
<<~RUBY
factory :#{factory_name}#{explicit_class_option} do
#{factory_attributes.gsub(/^/, " ")} # HERE IS WHERE I AM CALLING factory_attributes
end
RUBY
end
def factory_attributes # THIS METHOS IS NOT FOUND
attributes.map { |attribute|
"#{attribute.name} { #{attribute.default.inspect} }"
}.join("\n")
end
end
end
end
我能够获得我的看跌期权价值,但我也遇到了这个错误
#FactoryBot::Generators::ModelGenerator:0x00007f90c367b7f8 (NameError)
的未定义局部变量或方法“factory_name”
我不确定如何前进。
你应该尽量不要添加到 lib/generators/factory_bot/model/model_generator.rb
文件,但您应该在 lib/templates/factory_bot/model/factories.erb
处创建自定义工厂
FactoryBot.define do
factory :<%= "#{class_name.gsub("::", "").underscore}#{explicit_class_option}" %> do
<%=
attributes.map { |attribute|
results = " #{attribute.name} "
if attribute.name == 'name'
results = results + "{ Faker::Name.name }"
elsif
...
else
results = results + "{ #{attribute.default.inspect} }"
end
results
}.join("\n")
%>
end
end
我刚刚将 factory_bot's model_generator 复制到我的文件中 #lib/generators/factory_bot/model/model_generator.rb
这将是我开始进行更改的基准。 我能够通过更改
来证明它正在读取我的文件需要“generators/factory_bot” 要求“factory_bot_rails”
module FactoryBot
module Generators
class ModelGenerator < FactoryBot::Generators::Base
puts 'my file'
def factory_definition
<<~RUBY
factory :#{factory_name}#{explicit_class_option} do
#{factory_attributes.gsub(/^/, " ")} # HERE IS WHERE I AM CALLING factory_attributes
end
RUBY
end
def factory_attributes # THIS METHOS IS NOT FOUND
attributes.map { |attribute|
"#{attribute.name} { #{attribute.default.inspect} }"
}.join("\n")
end
end
end
end
我能够获得我的看跌期权价值,但我也遇到了这个错误
#FactoryBot::Generators::ModelGenerator:0x00007f90c367b7f8 (NameError)
的未定义局部变量或方法“factory_name”我不确定如何前进。
你应该尽量不要添加到 lib/generators/factory_bot/model/model_generator.rb
文件,但您应该在 lib/templates/factory_bot/model/factories.erb
处创建自定义工厂FactoryBot.define do
factory :<%= "#{class_name.gsub("::", "").underscore}#{explicit_class_option}" %> do
<%=
attributes.map { |attribute|
results = " #{attribute.name} "
if attribute.name == 'name'
results = results + "{ Faker::Name.name }"
elsif
...
else
results = results + "{ #{attribute.default.inspect} }"
end
results
}.join("\n")
%>
end
end