Hendra Nicholas I am a software engineer, consultant and CEO at 41studio currently living in West Java, Indonesia. My interests range from programming to sport. I am also interested in entrepreneurship, technology, and design.

Respect with RSpec in Rails

3 min read

rspec rails

RSpec was created by Steven Baker in 2005. Steven had heard about BDD from Aslak Hellesøy, who had been working on a project with Dan North when the idea first came to light. Steven was already interested in the idea when Dave Astels suggested that with languages like Smalltalk and Ruby, we could more freely explore new TDD frameworks that could encourage focus on behavior and then RSpec was born.

RSpec is a library that focus on testing the behavior of your everyday project, maybe some people not using rspec because the testing practice is the most difficult for a developer to learn, but honestly it can save your live. In the long term, you will not have to check your web page everytime you make a new feature, but you just have to check if your test failed.

The important thing is why we should create test for our application, and I can give you the simplest one answer. *Cause we want keeping our application healthy. It means no bugs left in application and then, why we should use Rspec for testing application in Rails? *Cause it has so many benefits. Here are some of them :

  1. Save your time.

  2. Frequently faster to run multiple verifications of your code as an automated test than to always check manually.

  3. Only going to increase as the code gets more complex.

  4. You’ll have better-designed code in which you’ll have more confidence.

  5. The most important benefit is that if you do testing well, you’ll notice that your work goes faster.

  6. Easier to find the bugs.

  7. Easier to add new features and easier to modify existing ones.

Before we start using Rspec, we need some configuration we need to add some gems in your Gemfile :

group :test, :development do

gem 'rspec-rails', '~> 2.0'

gem 'factory_girl_rails', '~> 4.0'

gem 'faker'


group :test do

gem 'shoulda-matchers', '~> 1.5.2'


bundle install

rails generate rspec:install

Although the syntactic details have evolved since Steven’s original version of RSpec, the basic premise remains. We use RSpec to write executable examples of the expected behavior of a small bit of code in a controlled context. Here’s how that might look :

describe Student do

context 'when first created' do

it 'should be empty' do

movie_list = MovieList.new

movie_list.should be_empty




describe() is method that what will we tested. context() is what condition that what we wanna tested. it() is method that creates an example of the behavior of what we described. The methods above known as scenario. After we understand about concept in RSpec, we will continue to the real code.

What Needs to Be on The Test of An Application ?

Model, View, Controller, Helper, and Routing. For now, I just explain about test in Model and Controller. Let’s say we have one model that name is Post.

class Post < ActiveRecord::Base

attr_accessible :title, :description, :user_id

has_many :comments

belongs_to :user

validates :title, :description, :presence => true

def self.search(search)

condition = []

fields = [:title, :description]

fields.each do |field|

condition(["LOWER(?) LIKE :search", :search])


if search

where(condition.join(' OR '), {:search => "%#{search.downcase}%"})






How Can We Test It ?

[code language=”ruby”] require ‘spec_helper’ describe Post do context ‘check the attribute accessible’ do it { should allow_mass_assignment_of :title } it { should allow_mass_assignment_of :description } it { should allow_mass_assignment_of :user_id } end context ‘check relation’ do it { should have_many :comments } it { should belong_to :user } end context ‘check search function’ do describe ‘.search’ do before do @post = FactoryGirl.create(:post, description: ‘Respect with Rspec’) end context ‘searching post with available result’ do it ‘should detect post’ do result = Post.search(‘Respect’) result.should include (@post) end end context ‘searching post with no result’ do it ‘should not detect post’ do result = Post.search(‘lorem ipsum’) result.should_not include(@post) end end [/code]

It’s so simple, right ?

How About Test Controller ?

Let’s say we wanna test dashboard controller

[code language=”ruby”] class DashboardController &amp;lt; ApplicationController before_filter :authenticate_user! def index @posts = Post.all end end [/code]

From above we saw that dashboard controller have authenticate user as before filter. Can we test it? Of course First of all, we should create file controller_macros.rb in spec/support.

[code language=”ruby”] module ControllerMacros def login_user before(:each) do @request.env[‘devise.mapping’] = Devise.mappings[:user] user = User.create!( email: Faker::Internet.email, password: ‘password’, first_name: Faker::Name.first_name, last_name: Faker::Name.last_name, provider: [‘facebook’, ‘google_oauth2’].sample, uid: 1_000_000_000_000_000_000 + Random.rand(10_000_000_000_000 – 1_000_000_000_000) ) user.full_name = ‘Fitria Rahmaani’; sign_in user end end end [/code]

And then, we can call login_user in our rspec test.

[code language=”ruby”] require ‘spec_helper’ require ‘awesome_print’ describe DashboardController do context ‘index’ do context ‘without login condition’ do it ‘should failed to access index page’ do get :index error = ‘You are being redirected.’ response.body.should eq(error) end end context ‘with login condition’ do login_user it ‘should success to access index page’ do get :index response.code.should == &amp;amp;quot;200&amp;amp;quot; end end end end [/code]

In above, we saw about FactoryGirl? What for? It’s for create and collect data that can be used for test an object. (spec/factories.rb)

[code language=”ruby”] require ‘faker’ require ‘factory_girl’ FactoryGirl.define do factory : event do title ‘Lorem ipsum’     description ‘Lorem ipsum dolor sir amet’ end end [/code]

And the last is, what we can test all code that we’ve created ?

Just type


And also, if you work with Sublime Text, you can install Rspec as package in your Sublime Text. So you can Run RSpec test inside Sublime Text. Just ctrl+shift+p, and type Install Package. And then search RspecBuild.

For more details about run Rspec test in Sublime Text, you can follow www.noppanit.com

Are you a Ruby on Rails enthusiast who want to face some challenges as a Back-end Developer to widen your knowledge and sharpen your skills? Then 41studio is your place! Apply to us and we will contact you shortly.

Any thought about “Respect with RSpec in Rails“? Comment below!

Hendra Nicholas I am a software engineer, consultant and CEO at 41studio currently living in West Java, Indonesia. My interests range from programming to sport. I am also interested in entrepreneurship, technology, and design.