Back

rails - rspec - 在Rails项目中增加rspec (add rspec to rails and test lib files)

发布时间: 2014-08-10 02:09:00

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

测试lib文件

例子: make sure your have this:

# config/application.rb
config.autoload_paths += %W(#{config.root}/lib)

test a file in lib folder:

require 'rails_helper' # 这句话极度重要. 
require 'html_parser'  # it's not require 'lib/html_parser'
describe HtmlParser do

  it 'should parse html_content' do
    puts 'hihihi'
  end 

end

3. 在 spec/spec_helper.rb 中,增加: 

# 适当的位置
config.expect_with(:rspec) { |c| c.syntax = :should }

对controller进行测试

例子: (把它无脑流拿来复制,稍微修改下就好了。不必测试model, view, routes, request啥的了)

require 'rails_helper'
describe DishesController do
  render_views

  before do
    admin_login
    request.env["HTTP_REFERER"] = root_path
    @dishes_category = DishesCategory.create :name => "烧烤"
    @dish = Dish.create :name => "羊肉串", :dishes_category_id => @dishes_category.id
  end

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

  it 'should get show' do
    get :show, :id => @dish.id
    response.should be_success
  end

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

  it 'should post create' do
    post :create,
      :dish => {
        :name => "五花肉"
      }
    Dish.last.name.should == "五花肉"
  end

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

  it 'should put update' do
    put :update,
      :id => @dish.id,
      :dish => {
        :name => "五花肉"
      }
    Dish.find(@dish.id).name.should == "五花肉"
  end

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

如果项目中用到了devise, 还需要: 

0. 建立一个 Admin model。 如果你是默认的Devise, 那就把下面的Admin都替换成 User.

1. rails_helper中:

RSpec.configure do |config|
  
  # 增加这一行:
  config.include Devise::TestHelpers, :type => :controller
end

def admin_login
  sign_in Admin.create(email: '[email protected]', password: '88888888')
end
测试用的某个文件(注意其中的before do...) :
# -*- encoding : utf-8 -*-
require 'rails_helper'

describe SystemSettingsController do
  before do
    admin_login
  end 

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

Back