[在将dev_factor_bot_rails gem包含在您的dev和Gemfile中的测试块中时,rails将在生成模型时自动生成工厂。
生成模型后,有没有办法生成工厂?
Eduardo Santana's ANSWER SHOULD BE CORRECT
注意:FactoryBot以前被命名为FactoryGirl
--fixture-replacement
选项可让您告诉Rails为构建测试数据生成什么。您可以在config/application.rb
文件中将此设置为默认值,如下所示:
config.generators do |g|
g.fixture_replacement :factory_girl
end
首先,查看源项目以了解其实现方式:
之后,尝试猜测其工作方式:
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
记住,当您使用滑轨g时,始终可以使用滑轨d撤消它
rails d factory_bot:model Car name speed:integer
注意:FactoryBot以前被命名为FactoryGirl
这对我有用rails g factory_bot:model User运行命令或只是将命令放出来。您仍然必须填写值。
@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
如果使用的是RSpec,并且想在spec/factories
目录中创建工厂,请使用以下命令
rails g factory_girl:model Car name speed:integer --dir spec/factories
这里有一些不错的答案,但是另一种选择是使用stepford。对于某些使用具有外键约束的架构的项目,deep_ *方法等可能会有所帮助,这是通过命令行生成工厂的简单方法。