How to Setup RSpec on a Rails Project

iamak

Ajithkumar P S

Posted on November 30, 2023

How to Setup RSpec on a Rails Project

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


Enter fullscreen mode Exit fullscreen mode

2. Install gems



group :development, :test do
  gem 'rspec-rails', '~> 6.1.0'
  gem 'factory_bot_rails'
  gem 'faker'
end


Enter fullscreen mode Exit fullscreen mode

3. Run below commands



bundle install
rails g rspec:install


Enter fullscreen mode Exit fullscreen mode

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



Enter fullscreen mode Exit fullscreen mode

Almost done. Now generate the user model



rails generate model User email:string password:string
rails db:migrate


Enter fullscreen mode Exit fullscreen mode

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


Enter fullscreen mode Exit fullscreen mode

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


Enter fullscreen mode Exit fullscreen mode

To know more:

rspec-rails
factory_bot_rails
faker

It's done

I hope this helps you to start your journey on rspec 🚀. Thanks for reading!

💖 💪 🙅 🚩
iamak
Ajithkumar P S

Posted on November 30, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related