How To Write Rspec

How To Write Rspec

15 Sep 2022
How To Write Rspec


  • The RSpec is a testing device for Ruby, created for behavior-driven development (BDD). It is the most often involved testing library for Ruby production applications. Even though it has a very rich and powerful DSL (domain-specific language), at its core it is a simple tool that you can start using rather quickly

Rspec setup for testing application:-

  • First, let’s create a Rails app using rail's new

rails new Demo -T

You can utilize any application name you need, the — T flag is used to tell Rails not to utilize MiniTest. By default, Rails will use a test system called ‘MiniTest’ on the off chance that we didn’t indicate — T flag, we need to use Rspec as the test framework rather than MiniTest.

  • Install Rspec-rails

RSpec-rails is the RSpec testing framework, in addition to a few takes on Rail’s magic. For example, when you run rails to produce model User to make user, it will also consequently create a model test record for that client: user_spec.rb.

  • Add this in your applications gem file inside the:development, test group :

# Gemfile

# …

group :development, :test do

gem ‘rspec-rails’


  • Then, at that point, run bundle install to install them.
  • In the wake of introducing these pearls, we actually need to introduce Rspec into our application utilizing
  • rails to create RSpec:install
  • Make sure to require the web driver's gem at the top of spec/rails_helper.rb:

require ‘spec_helper’

require ‘web drivers’

  • Let’s create a controller StaticControllerwith just a single action index:
  • This will make stariv_controller.rb and static/index.html.erb. Then, open static/index.html.erb, and add a static text, saying ‘Hello World’ into it.
  • Then check your output using rails s.
  • Write your first test

Now create a file named “static_spec.rb” , and place it in “spec/static_spec.rb”

# spec/static_spec.rb

require ‘rails_helper’

RSpec.describe ‘Static content’, type: :system do

it ‘shows the static text’ do

visit static_index_path

expect(page).to have_content(‘Hello world’)



  • Then, at that point, in your terminal, navigate to your Rails application root path, then run.
  • rspec spec/static_spec.rb

You should see your default Browser open and it will load the page briefly and close, and a succeeded test :

Congratulation! You have written your first Rspec test!!!

Leave a comment: