创建演示应用
rails new sample_app_1 --database=mysql
cd sample_app_1
bundle install --without production
配置 `config/database.yml`
bin/rails db:create
bin/rails test
bin/rails s
打开 http://127.0.0.1:3000
生成静态页面
生成 StaticPages 控制器
bin/rails generate controller StaticPages home help
撤销操作
rails generate controller StaticPages home help
rails destroy controller StaticPages home help
rails generate model User name:string email:string
rails destroy model User
rails db:migrate
rails db:rollback
如果要回到最开始的状态,可以使用:
rails db:migrate VERSION=0
修改静态页面的内容
编辑 app/views/static_pages/home.html.erb,修改内容
<h1>Sample App</h1>
<p>
This is the home page for the
<a href="https://www.railstutorial.org/">Ruby on Rails Tutorial</a>
sample application.
</p>
编辑 app/views/static_pages/help.html.erb
<h1>Help</h1>
<p>
Get help on the Ruby on Rails Tutorial at the
<a href="https://www.railstutorial.org/help">Rails Tutorial Help page</a>.
To get help on this sample app, see the
<a href="https://www.railstutorial.org/book"><em>Ruby on Rails Tutorial</em>
book</a>.
</p>
编辑 config/routes.rb,增加 root
Rails.application.routes.draw do
get 'static_pages/home'
get 'static_pages/help'
root "static_pages#home"
end
开始测试
编辑 test/controllers/static_pages_controller_test.rb,给 about 页面添加测试代码
require "test_helper"
class StaticPagesControllerTest < ActionDispatch::IntegrationTest
test "should get home" do
get static_pages_home_url
assert_response :success
end
test "should get help" do
get static_pages_help_url
assert_response :success
end
test "should get about" do
get static_pages_about_url
assert_response :success
end
end
bin/rails test
测试失败
需要 Controller 添加 about 方法,添加页面 about.html.erb,添加路由,才能通过测试。
测试页面标题
编辑 test/controllers/static_pages_controller_test.rb,添加测试代码
require "test_helper"
class StaticPagesControllerTest < ActionDispatch::IntegrationTest
def setup
@base_title = "Ruby on Rails Tutorial Sample App"
end
test "should get home" do
get static_pages_home_url
assert_response :success
assert_select "title", "Home | #{@base_title}"
end
test "should get help" do
get static_pages_help_url
assert_response :success
assert_select "title", "Help | #{@base_title}"
end
test "should get about" do
get static_pages_about_url
assert_response :success
assert_select "title", "About | #{@base_title}"
end
end
同时在这三个页面中需要添加对应的 title