Skip to content

Commit 78075a6

Browse files
committed
Add AuthenticationGenerator for users factory creation
This change addresses an issue where running the `factory_bot` generator could result in a `factory_bot [not found]` error. The problem occurred due to missing generator definitions and template files. With this update, the authentication generator is properly defined and includes the necessary templates, ensuring that the `users.rb` factory file is generated regardless of whether the project is using RSpec (`spec/factories`) or Minitest (`test/factories`). This guarantees consistent behavior and avoids generator errors in environments without a `spec` directory. Previously, projects without a `spec` directory or with incomplete generator/template setup would fail when invoking `factory_bot` generators, making it impossible to scaffold the necessary factory files automatically. - Added the missing `factory_bot:authentication` generator definition. - Included `users.rb` template under `templates` directory. - Implemented logic to detect the test framework and place the generated factory file in the correct directory (`spec/factories` or `test/factories`). - Ensured generator runs successfully regardless of the presence of a `spec` directory.
1 parent 364bd89 commit 78075a6

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
# frozen_string_literal: true
2+
3+
require "generators/factory_bot"
4+
require "factory_bot_rails"
5+
require "fileutils"
6+
7+
module FactoryBot
8+
module Generators
9+
class AuthenticationGenerator < Base
10+
def create_users_factory
11+
dir = factories_dir
12+
FileUtils.mkdir_p(dir)
13+
14+
target = File.join(dir, "users.rb")
15+
if File.exist?(target)
16+
say_status :skip, "users.rb already exists at #{target}", :yellow
17+
else
18+
template "users.rb", target
19+
say_status :create, target, :green
20+
end
21+
end
22+
23+
private
24+
25+
def factories_dir
26+
if Dir.exist?(Rails.root.join("spec"))
27+
Rails.root.join("spec", "factories").to_s
28+
else
29+
Rails.root.join("test", "factories").to_s
30+
end
31+
end
32+
end
33+
end
34+
end
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
# frozen_string_literal: true
2+
3+
FactoryBot.define do
4+
factory :user do
5+
password { "password123" }
6+
password_confirmation { "password123" }
7+
email_address { "user#{SecureRandom.hex(3)}@example.com" }
8+
end
9+
end

0 commit comments

Comments
 (0)