如果在Gemfile的dev和test blocks中包含factory_bot_rails gem,则当rails生成模型时,它会自动生成工厂。
是否有一种方法可以在生成模型后生成工厂?
注意:FactoryBot以前叫做FactoryGirl。
如果在Gemfile的dev和test blocks中包含factory_bot_rails gem,则当rails生成模型时,它会自动生成工厂。
是否有一种方法可以在生成模型后生成工厂?
注意:FactoryBot以前叫做FactoryGirl。
首先,查看源代码以了解它是如何实现的:
然后,尝试猜测它是如何工作的:
rails g factory_bot:model Car name speed:integer
结果是:
create test/factories/cars.rb
并且内容为:
# Read about factories at https://github.com/thoughtbot/factory_girl
FactoryBot.define do
factory :car do
name "MyString"
speed 1
end
end
记住,在使用 "rails g" 命令时,您始终可以使用 "rails d" 命令撤消它。
rails d factory_bot:model Car name speed:integer
注意:FactoryBot
以前的名称是FactoryGirl
spec
目录下创建它? - juliangonzalezrails g factory_girl:model User --dir spec/factories
- marman--fixture-replacement
选项允许您告诉Rails生成什么来构建测试数据。您可以在config/application.rb
文件中将其设置为默认值,如下所示:
config.generators do |g|
g.fixture_replacement :factory_bot, suffix_factory: 'factory'
end
--fixture-replacement
? - Arnold Roarails g model
命令之后调用的生成器命令,而不是使用模式描述在模式中创建魔法工厂。该选项在此处进行了讨论:https://github.com/thoughtbot/factory_girl_rails/issues/63。@edouardo-santana 和 @cjhveal 的答案都是可以接受的。 - fro_oo我有一个宝石插件可以完美解决这个问题 https://github.com/markburns/to_factory
我使用rails g factory_bot:model User命令,可以实现这个功能,无论是运行该命令还是直接输出puts'ing该命令都可以。但您仍然需要填写值。
@run_command = true
@force = true
@columns_to_ignore = %w[id created_at update_at]
@tables_to_ignore = %w[schema_migrations ar_internal_metadata]
tables = ActiveRecord::Base.connection.tables.reject{|t| (@tables_to_ignore || []).include?(t)}
tables.each do |table|
klass = table.singularize.camelcase.constantize
command = "rails g factory_bot:model #{klass.to_s} #{klass.columns.reject do |c|
(@columns_to_ignore || []).include?(c.name)
end.map do |d|
"#{d.name}:#{d.sql_type == 'jsonb' ? 'json' : d.type}"
end.join(' ')}"
command << ' --force' if @force
puts command
puts %x{#{command}} if @run_command
puts (1..200).to_a.map{}.join('-')
end
将Factory Bot配置为测试中的数据生成器工具,以便您无需手动创建数据生成器。
在config/application.rb
文件中:
config.generators do |g|
g.test_framework :rspec, fixture: true
g.fixture_replacement :factory_bot, dir: 'spec/factories'
end
并不完全相关。
我也创建了一个宝石, 用于从现有数据构建工厂。
希望可以帮助您加快流程速度......
puts FactoryBotFactory.build(User.new, file_path: 'spec/factories/user.rb')
puts FactoryBotFactory.build(User.last, file_path: 'spec/factories/user.rb')
# example output from User.new
FactoryBot.define do
factory :user, class: User do
id { nil }
name { nil }
created_at { nil }
updated_at { nil }
display_name { nil }
image_url { nil }
is_active { true }
end
end
如果您需要构建虚假数据,您还可以配置自定义转换器。
gem install schema_to_scaffold
安装并运行scaffold -f
命令。这里有一些不错的答案,但另一个选择是使用stepford。对于一些使用具有外键约束的模式的项目,deep_*方法等可能会有所帮助,而且通过命令行生成工厂的方法也很简单。