How To Write Rspec

By: Apurva Karankar Category: Ruby on Rails, Web Development Technologies: Ruby on Rails
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 rails 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 took on Rail’s magic. For example, when you run rails 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’
end
- 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 create RSpec:install
- Make sure to require the web drivers 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, say ‘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’)
end
end
- 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!!!
Originally published at https://www.cryptextechnologies.com.