rails-tutorials: static page and automated testing

生成静态页面的控制器

1
rails generate controller StaticPages home help

撤销操作

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

TDD

test/controllers/static_pages_controller_test.rb

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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

app/views/static_pages/home.html.erb

通过<% … %>调用Rails提供的provide函数,把字符串”Home”赋给:title。11然后,在标题中,我们使
用类似的符号<%= … %>,通过Ruby的yield函数把标题插入模板中。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<% provide(:title, "Home") %> 
<!DOCTYPE html>
<html>
<head>
<title><%= yield(:title) %> | Ruby on Rails Tutorial Sample App</title>
</head>

<body>
<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>
</body>
</html>

为了提取出共用的结构,Rails 提供了一个特别的布局文件,名为 application.html.erb。

app/views/layouts/application.html.erb

1
2
3
4
5
6
7
8
9
10
11
12
13
 <!DOCTYPE html>
<html>
<head>
<title><%= yield(:title) %> | Ruby on Rails Tutorial Sample App</title>
<%= csrf_meta_tags %>
<%= csp_meta_tag %>
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
<%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>
</head>
<body>
<%= yield %>
</body>
</html>

这几行代码的作用是,引入应用的样式表和 JavaScript 文件; Rails 提供的 csp_meta_tag 方法实现内容安全策略(Content Security Policy,CSP),避免遭受跨站脚本(cross-site scripting,XSS)攻击;Rails 提供的 csrf_meta_tags 方法用于避免跨站请求伪造(Cross-Site Request Forgery,CSRF)攻击。

app/views/static_pages/home.html.erb

1
2
3
4
5
6
7
8
<% provide(:title, "Home") %> 

<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>

<%= yield %>这行代码的作用是,把每个页面的内容插入布局中。在布局 中使用这行代码后,访问 /static_pages/home 时会把 home.html.erb 中的内容转换成 HTML,然后插入 <%= yield %> 所在的位置。

Donate article here