Tuesday, March 25, 2014

Testing with RSpec

Part 1: Installation

Add rspec-rails to both the :development and :test groups in the Gemfile:

group :development, :test do
  gem 'rspec-rails', '~> 3.0.0.beta'
end

Download and install by running:

$ bundle install

Initialize the spec/ directory (where specs will reside) with:

$ rails generate rspec:install

This adds spec/spec_helper.rb and .rspec files that are used for configuration. See those files for more information.

To run your specs, use the rspec command:

$ bundle exec rspec

# Run only model specs
$ bundle exec rspec spec/models

# Run only specs for AccountsController
$ bundle exec rspec spec/controllers/accounts_controller_spec.rb

Specs can also be run via rake spec, though this command may be slower to start than the rspec command.

Part 2: RSpec

Create a new file at /spec/user_spec.rb and copy these into the file.

require 'spec_helper'

describe User do
  # create
  before :each do
    @user = User.create(:username => "kirby510", :email => "kirby.kl05@yahoo.com", :password => "kirby510", :name => "Lee Kian Theng", :nickname => "Student Kirby")
    @user.add_role :admin
  end

  # correct condition
  it "#name" do
    @user.name.should == "Lee Kian Theng"
  end

  # false condition
  it "name is should not null" do
    @user.name.should == nil
    # @user.name.should_not == nil
  end

  # check role
  it "#role" do
    # puts @user.roles.first.name
    @user.roles.first.name.should == "admin"
  end

  # update
  it "can update" do
    @user.update_attributes(:username => "kirby510", :email => "kirby.kl05@yahoo.com", :password => "kirby510", :name => "Lee Kian Leong", :nickname => "Student Kirby 2012")
    @user.nickname.should == "Student Kirby 2012"
  end

  # destroy
  it "can delete" do
    @user.destroy
  end
end

$ rspec spec/user_spec.rb

rspec/rspec-rails · GitHub
Return to Internship Note (LoanStreet)
Previous Episode: Create User Profile Rails App
Next Episode: Capybara with RSpec & Rails 3

0 comments:

Post a Comment