Factory Girl / Rails: Generator to create a factory for existing model?
Asked Answered
R

2

9

I am using the rspec_rails and factory_girl_rails gems within my Rails project. All of the models are already created. Is there a generator that I can run that will create the factory file for an existing model?

Ex: I already have a Blog model. RSpec allows me to generator a model spec file at spec/models/blog_spec.rb by simply running the following:

rails generate rspec:model blog

Is there a generator that I can run in the command line that will generate the factory file for this existing model, located at: spec/factories/blogs.rb?

I did not see any mentions of generators within the factory_girl_rails docs.

Response answered 27/2, 2016 at 5:19 Comment(0)
H
11

First configure Factory Bot.

config.generators do |g|
  g.fixture_replacement :factory_bot, dir: "spec/factories"
end

Then run the generator.

rails g factory_bot:model Blog name description total_visits:integer
Harvester answered 27/2, 2016 at 6:1 Comment(1)
FactoryGirl became FactoryBot. So it is now rails g factory_bot:model Blog.Spree
T
1

Updated Answer

Factory Girl has been renamed as Factory Bot

  1. Make sure to add factory_bot_rails gem in development & test group
  2. Then run rails g factory_bot:model Blog name description total_visits:integer

Example:


group :development, :test do
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
  gem 'pry-rails'
  gem 'rspec-rails', '~> 5.0.0'
  gem 'factory_bot_rails'
end
Transitory answered 4/7, 2021 at 5:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.