rspec---单元测试

配置环境

  1. add to Gemfile:
    1
    2
    3
    4
    5
    6
    7
    8
    # Gemfile: 
    gem 'rspec-rails', '~> 3.5.2'
    然后运行:
    $ bundle exec rails generate rspec:install
    记得要把生成的.rspec 文件做个修改,删掉
    # .rspec file:
    --color
    # NO --warning, --require spec_helper
  1. 下面是测试lib文件的一个例子: make sure your have this:

config/application.rb

config.autoload_paths += %W(#{config.root}/lib)
test a file in lib folder:

1
2
3
4
5
6
7
8
9
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

测试文件示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
require 'rails_helper'
describe OrderDishesLabelsController do
render_views
before do
admin_login
request.env["HTTP_REFERER"] = root_path
@order_dishes_label = OrderDishesLabel.create :name => "多辣"
end
it 'should get index' do
get :index
response.should be_success
response.code.should == '200'
end
it 'should get show' do
get :show, :id => @order_dishes_label.id
response.should be_success
assigns(:order_dishes_label).name.should == "多辣"
end
it 'should get new' do
get :new
response.should be_success
end
it 'should post create' do
name = "少盐"
post :create,
{
:order_dishes_label => {
:name => name
}
}
OrderDishesLabel.last.name.should == name
end
it 'should get edit' do
get :edit, :id => @order_dishes_label.id
response.should be_success
end
it 'should put update' do
new_name = "少糖"
put :update,
{
:id => @order_dishes_label.id ,
:order_dishes_label => {
:name => new_name
}
}
OrderDishesLabel.find(@order_dishes_label.id).name.should == new_name
end
it 'should delete destroy' do
size_before_delete = Order_dishes_label.all.size
delete :destroy, :id => @order_dishes_label.id
Order_dishes_label.count.should == size_before_delete - 1
end
end

测试:
bundle exec rspec 文件名