A simple instruction to Rspec – 3 in Ruby on Rails -4

This is small introduction about rspec version 3 for ruby on rails developers, and also note that this is not mean for techy geeks 🙂

Initial Setup
add gem 'rspec-rails', '~> 3.0.0'

then bundle install

And run rails generator rspec:install

Herein after spec files are automatically created when ever you create model, controller, view files, if you dont want any spec file to be created automatically then
in your application.rb

config.generators do |g|
g.test_framework :rspec,
view_specs: false,
helper_specs: false,
routing_specs: false,
controller_specs: true,
request_specs: false
end

put false wherever you dont want to create spec files
RSpec generators can also be run independently. For instance,

rails generate rspec:model post

All specs are created inside spec folder and to run test just type rspec in terminal

If you want to test only a particular file say products.rb in model then

 rspec ../rails_app/spec/models/products.rb

Thats all

Model specs

Examples
require "rails_helper"

describe Post do
it “checks it saves the data” do
expect(Post.count).to eq 0
@post=Post.create
@post.save
expect(Post.count).to eq 1
end
end

controller spec

require 'rails_helper'

RSpec.describe WelcomeController, :type => :controller do
it ‘has 300 status code’ do
get :index
expect(response.status).to eq(200)
end
end

Matchers

rspec-rails offers a number of custom matchers, most of which are
rspec-compatible wrappers for Rails’ assertions.

redirects
expect(response).to redirect_to(path)
templates
expect(response).to render_template(template_name)
assigned objects
expect(assigns(:widget)).to be_a_new(Widget)

Advertisements

One thought on “A simple instruction to Rspec – 3 in Ruby on Rails -4

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s