At the time of writing this article using ruby 3.2.0 & Rails 7.1.2
Let's get started...
1. Create a new project
rails new rspec-test-app -d postgresql
cd rspec-test-app
rails db:create
rails s
2. Install gems
group :development, :test do
gem 'rspec-rails', '~> 6.1.0'
gem 'factory_bot_rails'
gem 'faker'
end
3. Run below commands
bundle install
rails g rspec:install
4. Configure factory bot
Create spec/support/factory_bot.rb file then copy & paste below code
# spec/support/factory_bot.rb
require 'rails_helper'
RSpec.configure do |config|
config.include FactoryBot::Syntax::Methods
end
Almost done. Now generate the user model
rails generate model User email:string password:string
rails db:migrate
It will generate following files for us:
invoke active_record
create db/migrate/20231130055533_create_users.rb
create app/models/user.rb
invoke rspec
create spec/models/user_spec.rb
invoke factory_bot
create spec/factories/users.rb
Now run the below command and the watch the output
rspec
*
Pending: (Failures listed here are expected and do not affect your suite's status)
1) User add some examples to (or delete) /home/spritle/p/rspec-test-app/spec/models/user_spec.rb
# Not yet implemented
# ./spec/models/user_spec.rb:4
Finished in 0.00287 seconds (files took 0.64832 seconds to load)
1 example, 0 failures, 1 pending
To know more:
rspec-rails
factory_bot_rails
faker
I hope this helps you to start your journey on rspec 🚀. Thanks for reading!
Top comments (0)