第三天,Ruby on Rails,脚手架的应用,自动化测试

2018年12月1日

一、脚手架应用

我这次换了新版本的ruby环境,2.5.3

换源,并设置ruby2.5.3为默认版本

$ gem source --add https://gems.ruby-china.com/ --remove https://rubygems.org/
$ rvm use 2.5.3 --default

新建一个项目

$ rails new toy_app
$ cd toy_app
$ bundle install 

记得在 $ bundle install之前修改Gemfile文件,把对应想要用到的gem包及具体版本加进去,如果有不想用的,就使用命令

$ gem install without 不想安装的gem包名

把对应包加入Gemfile.lock文件。

建好项目后可以先初始化仓库,commit,并push到远程端,然后部署到heroku

$ git init
$ git add -A
$ git commit -m "Initialize repository"
$ git remote add origin https://gitee.com/your name/your repository.git
$ git push -u --all

$ heroku create
$ git push heroku master

然后我们就要用到脚手架来快速搭建一个User模型,包含两个字段,name和email:

$ rails generate scaffold User name:string email:string

然后迁移数据库,建一个User表:

扫描二维码关注公众号,回复: 4517540 查看本文章
$ rails db:migrate #rails5以上版本使用命令
$ rake db:migrate #rails旧版本命令

执行之后就可以看到数据库新建了一个User表,并且已经可以访问对应页面了。执行$ rails server,然后在浏览器输入localhost:3000/users,就可以看到用户界面了。rails已经为我们自动创建了增删改查的功能,非常方便。

如果想要删除这个User模型,就用destroy命令,destroy命令是和generate相反的命令:

$ rails destroy model User

接着建一个micropost资源用来给用户发微博。

$ rails generate scaffold Micropost content:text user_id:integer
$ rails db:migrate

再运行就可以看到localhost:3000//microposts页面了,同样有增删改查功能:

接下来可以给微博添加一些验证信息,比如说最长不超过40字符,在app/models/micropost.rb里面添加一句话

class Microposts < ApplicationRecord
  validates :content,length:{maximum:40}
end

如果输入字符太多就会报错:

接下来的内容我就不仔细讲了,参考书Ruby on Rails Tutorial(Michael Hartl)

记得每次做完提交一下,再推送到远程仓库。

脚手架虽然方便快捷,但是好多封装好的东西都没有真正理解,没有测试没有验证,所以初学者不要被它迷惑了,还是要扎扎实实的学基础,如果不用脚手架也可以实现脚手架的所有功能,你就不用再看这些教程了。

二、自动化测试

测试可以避免回归问题,减少查找问题的时间,rails在新建项目时已经为我们做了一个测试模块,只需要改动/test文件夹里的.rb文件即可,然后执行测试$ rails test完成测试。下面我们新建一个项目sample_app,再建两个静态页面做测试

$ rails new sample_app
$ sample_app 
$ bundle install
$ rails generate controller StaticPage home help
$ git add -A
$ git commit -m "Add a static page"
$ git push

然后打开sample_app/test/controllers/static_page_controller_test.rb文件,模仿home和help写一个about页面的测试,然后执行 $ rails test,这时肯定会报错,提示你在跟路由中没有找到about,这时,修改/config/routers.rb文件

Rails.application.routes.draw do
  get 'static_page/home'
  get 'static_page/help'
  get 'static_page/about'
end

再次运行$ rails test,仍报错,提示没有找到about方法,这时修改sample_app/app/controllers/static_page_controller.rb文件

class StaticPageController < ApplicationController
  def home
  end

  def help
  end

  def about
  end

end

再次运行$ rails test,仍报错,提示缺少template文件,此时,就是最后一步,在/sample_app/app/views/static_page/目录下新建一个文件about.html.erb,参考home和help的代码,复制过来修改一下内容,再次运行$ rails test ,就显示全部test通过了,此时访问localhost:3000/static_page/about,显示出页面则测试成功。就是一个完整的自动化测过程,先建立测试,再根据错误提示一步步的修改,增添文件,最后直到测试全部通过。

这次写的过程比较粗略,基本都是书上有的我就没写,有什么问题欢迎留言,共勉! 

猜你喜欢

转载自blog.csdn.net/yier_1/article/details/84702848
今日推荐