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)