欢迎来到cool的博客
7

Music box

Click to Start

点击头像播放音乐
新博客链接

Rails-rspec 单元测试

1. add to Gemfile:

# Gemfile: 
gem 'rspec-rails', '~> 3.0.0'

然后运行:

$ bundle exec rails generate rspec:install

记得要把生成的.rspec 文件做个修改,删掉

# .rspec file:
--color 
# NO --warning, --require spec_helper

单元测试主要针对controller进行测试

require 'rails_helper'
describe AboutsController do
  render_views

  before do
    admin_login
    request.env["HTTP_REFERER"] = root_path
    @about = About.create :title => '关于我们'
  end 

  it 'should get index' do
    get :index
    response.should be_success
  end 

  it 'should get show' do
    get :show, :id => @about.id
    response.should be_success
    assigns(:about).title.should == '关于我们'
  end 

  it 'should get new' do
    get :new
    response.should be_success
  end 

  it 'should post create' do
    title = '关于我们的最新消息。。。。'
    post :create, :about => {
      :title => title,
      :content => '我们公司是国内一流的。。。'
    }   
    About.last.title.should ==  title
  end

  it 'should get edit' do
    new_title = 'abcd'
    get :edit, :id => @about.id
    response.should be_success
  end

  it 'should put update' do
    new_title = 'abcd'
    put :update, :id => @about.id , :about => {
      :title => new_title
    }
    About.find(@about.id).title.should == new_title
  end

  it 'should delete destroy' do
    size_before_delete = About.all.size
    delete :destroy, :id => @about.id
    About.count.should == size_before_delete - 1
  end
end

tips:

1. 务必使用  $ rails generate rspec:install, 会生成 一个 spec_helper 和一个 rails_helper, 不要改动他们

2. 务必修改 rails帮你生成好的  rspec文件。  把第一行的 spec_helper 改成 rails_helper

#  require 'spec_helper'
require 'rails_helper‘ 

否则在运行时会报错,找不到rails相关的东西

 

返回列表