创建演示应用
创建工程
cd projects
rails new microblog
修改Gemfile
... ...
group :development, :test do
gem 'sqlite3'
gem 'byebug', platform: :mri
end
group :development do
gem 'web-console'
gem 'listen', '~> 3.0.5'
gem 'spring'
gem 'spring-watcher-listen', '~> 2.0.0'
end
group :test do
gem 'rails-controller-testing'
gem 'minitest-reporters'
gem 'guard'
gem 'guard-minitest'
end
group :production do
gem 'pg'
end
... ...
执行bundle
cd microblog
bundle install --without production
rails db:migrate
加入Git
git init
git add .
git commit -m "initialize microblog"
部署到Heroku
heroku login
heroku create
git push heroku master
heroku run rake db:migrate
heroku open
heroku logs # 查看Heroku日志
可以参考这篇文章。
静态页面
创建并切换Git分支
git checkout -b static-pages
在分支上工作是一个非常好的习惯,这样可以保证工作分支不会影响到主分支的内容,保障主分支是可用的,直到工作分支完成后,在合并入主分支。
生成静态页面
rails generate controller StaticPages home help
此时,查看路径localhost:3000/static_pages/home
可以看到:
修改静态页面
我们可以随意修改两个页面的内容,这里无需关注。
开始测试
执行测试
rails test
MiniTest报告程序
为了让Rails应用的测试适时显示红色和绿色,需要在测试辅助文件中加入以下内容:
# test/test_helper.rb
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'
require "minitest/reporters"
Minitest::Reporters.use!
... ...
添加测试
仿照生成的测试添加about页面的测试
# test/controllers/test.rb
... ...
test "should get about" do
get static_pages_about_url
assert_response :success
end
修改代码
根据测试结果给出的错误信息,不断修改代码:
# config/routes.rb
... ...
get 'static_pages/about'
# app/controllers/static_pages_controller
... ...
def about
end
添加app/views/static_pages/about.html.erb文件
直到执行测试通过:
重构代码
添加测试:
# test/controllers/static_pages_controller_test.rb
... ...
def setup
@base_title = "Microblog"
end
test "should get home" do
... ...
assert_select "title", "Home | #{@base_title}"
end
test "should get help" do
... ...
assert_select "title", "Help | #{@base_title}"
end
test "should get about" do
... ...
assert_select "title", "About | #{@base_title}"
end
end
修改布局文件:
# app/views/layouts/application.html.erb
<%= yield(:title) %> | Microblog
... ...
修改其他文件:
# app/views/static_pages/home.html.erb
<% provide(:title, "Home") %>
... ...
# app/views/static_pages/help.html.erb
<% provide(:title, "Help") %>
... ...
# app/views/static_pages/about.html.erb
<% provide(:title, "About") %>
... ...
同样的道理,可以添加Contact页面。
设置路由
# config/routes.rb
root "static_pages#home"
删除app/controllers/application_controller.rb
中的hello
函数。
测试根路由:
# test/controllers/static_pages_controller_test.rb
... ...
test "should get root" do
get root_url
assert_response :success
end
合并分支
git checkout master
git merge static-pages
git branch -d static-pages
git branch
欲知代码如何,使劲猛戳这里。当然也可以访问Heroku网址。
参考
《Rails Tutorial 4th》