Skip to content

Commit c0458f2

Browse files
committed
Add factory_bot_rails gem and create user_spec.rb and users.rb factory
1 parent 02f9864 commit c0458f2

File tree

6 files changed

+30
-1
lines changed

6 files changed

+30
-1
lines changed

Gemfile

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,7 @@ group :development, :test do
5656
# See https://guides.rubyonrails.org/debugging_rails_applications.html#debugging-with-the-debug-gem
5757
gem "debug", platforms: %i[ mri mingw x64_mingw ]
5858
gem 'rspec-rails'
59+
gem 'factory_bot_rails'
5960
end
6061

6162
group :development do

Gemfile.lock

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,11 @@ GEM
108108
concurrent-ruby (~> 1.0)
109109
zeitwerk (~> 2.6)
110110
erubi (1.12.0)
111+
factory_bot (6.4.2)
112+
activesupport (>= 5.0.0)
113+
factory_bot_rails (6.4.2)
114+
factory_bot (~> 6.4)
115+
railties (>= 5.0.0)
111116
globalid (1.2.1)
112117
activesupport (>= 6.1)
113118
i18n (1.14.1)
@@ -273,6 +278,7 @@ DEPENDENCIES
273278
debug
274279
devise
275280
devise-jwt
281+
factory_bot_rails
276282
importmap-rails
277283
jbuilder
278284
puma (~> 5.0)

app/models/user.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,6 @@ class User < ApplicationRecord
77

88
def generate_jwt
99
payload = { user_id: id, exp: 1.day.from_now.to_i }
10-
JWT::Encoder.encode(payload, Rails.application.credentials.devise_jwt_secret_key)
10+
JWT.encode(payload, Rails.application.credentials.devise_jwt_secret_key, 'HS256')
1111
end
1212
end

spec/factories/users.rb

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
FactoryBot.define do
2+
factory :user do
3+
email { '[email protected]' }
4+
password { 'password123' }
5+
end
6+
end

spec/models/user_spec.rb

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
require 'rails_helper'
2+
3+
RSpec.describe User, type: :model do
4+
describe 'generate_jwt' do
5+
it 'generates a valid JWT token' do
6+
user = create(:user) # Use FactoryBot to create a user
7+
8+
jwt_token = user.generate_jwt
9+
10+
decoded_token = JWT.decode(jwt_token, Rails.application.credentials.devise_jwt_secret_key, true, algorithm: 'HS256')
11+
expect(decoded_token[0]['user_id']).to eq(user.id)
12+
end
13+
end
14+
end

spec/rails_helper.rb

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,8 @@
3838
# instead of true.
3939
config.use_transactional_fixtures = true
4040

41+
config.include FactoryBot::Syntax::Methods
42+
4143
# You can uncomment this line to turn off ActiveRecord support entirely.
4244
# config.use_active_record = false
4345

0 commit comments

Comments
 (0)