从单元测试的角度为了保证我们写的函数,也就是从细粒度方便,来保证我们写的代码是没有问题的,所以测试还是很重要的。
测试本身呢,带来的好处也是非常多的。
1.比如说当我们项目中某一些依赖的第三方的gem或者一些功能升级的时候能保证我们的一些老的版本运行没有问题,就是进行一次全面的测试。
2.项目进行一次大的重构的时候,同时也能够快速和方便的知道对老的版本涉及的改动有多大,我们都是通过测试可以做到的。
3.可以简单的做些白盒测试,更加明白代码是不是我们所期望的,而不是结合页面做黑盒测试。
一.首先在GemFile引用gem
group :development, :test do
# Call 'byebug' anywhere in the code to stop execution and get a debugger console
gem 'byebug', platform: :mri
gem 'database_cleaner', '~> 1.5.3'
gem 'rspec-rails', '~> 3.5'
gem 'rails-controller-testing'
end
介绍:
第一个gem是作为和rspec整合使用的,就是保证我们当前的独立的case,数据库之前之后都会进行一个清空的操作,就是保证数据干干净净没有污染,用例之前不会因为数据污染造成一些问题。
第二个本身就是我们的rspec的测试框架。
第三个是因为我们在rails5之后的rspec把controller这个功能给剥离出来了,如果我们针对于controller做为测试的话,就需要引用这个gem。
二:rspec初始化
执行命令:
rails g rspec:install
说明:会帮我们生成rspec运行的配置文件
生成的.rspec可以把一些参数放在这里,就不用再指定rspec运行的参数了
rails_helper.rb和spec_helper.rb做为rspec的整体的配置文件而存在的
1.修改.rspec加上-f -d 可以打印出成功和失败
2.因为我们在gem中加上了database_cleanner,所以要在spec_helper加上database_cleanner的行为**
config.before(:suite) do
DatabaseCleaner.clean_with(:truncation)
end
config.before(:each) do
DatabaseCleaner.start
end
config.after(:each) do
DatabaseCleaner.clean
end
三:接下来就可以测试了
我们测试一般在spec文件下创建测试文件,比如测试Usercontroller
user_controller内容是:
class UsersController < ApplicationController
def new
@user = User.new
end
def create
@user = User.new(params.require(:user)
.permit(:email, :password, :password_confirmation))
if @user.save
flash[:notice] = "注册成功"
redirect_to root_path
else
render action: :new
end
end
end
我们首先在spec下创建一个controller文件夹
然后创建对应的名字加上spec,eg:users_controller_spec.rb
在里面写上
require 'rails_helper'
describe UsersController do
context "signup" do
it "should failed" do
post :create, params: { user: { email: 'railsboy' } }
expect(response).to render_template("new")
end
it "should success" do
post :create, params: { user:
{
email: 'railsboy@163.com',
password: '111111',
password_confirmation: '111111'
}
}
expect(response).to redirect_to(new_session_path)
end
end
end
四:运行命令
rspec
说明:这里会打印成功或者失败信息
网友评论