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

访问量: 1629

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

2. 下面是测试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

 下面是对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: 'admin@this.com', 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

订阅/RSS Feed

Subscribe

分类/category