Ruby on Rails 教程 (02)

专业级演示应用

最终完成的应用包含用户、微博功能,以及完整的登录和用户身份认证系统

  • 创建静态页面
  • 自动化测试

创建演示应用


$ cd ~/workspace
$ rails new sample_app
$ cd sample_app/
$ git ...

静态页面


$ rails generate controller StaticPages home help
$ rails s

http://localhost:3000/static_pages/home
http://localhost:3000/static_pages/about

修改首页HTML


<h1>Sample App</h1>
<p>
This is the home page for the
<a href="http://www.railstutorial.org/">Ruby on Rails Tutorial</a>
sample application.
</p>

修改帮助HTML


<h1>Help</h1>
<p>
Get help on the Ruby on Rails Tutorial at the
<a href="http://www.railstutorial.org/#help">Rails Tutorial help section</a>.
To get help on this sample app, see the
<a href="http://www.railstutorial.org/book"><em>Ruby on Rails Tutorial</em>
book</a>.
</p>a
          

开始测试

美化测试报告的GEM


# Gemfile
group :test do
  gem 'minitest-reporters', '1.0.5'
  gem 'mini_backtrace', '0.1.3'
  gem 'guard-minitest', '2.3.1'
end

$ bundle install

# test/test_helper.rb
require "minitest/reporters"
Minitest::Reporters.use!

第一个测试


# test/controllers/static_pages_controller_test.rb
$ rake test

变红


# test/controllers/static_pages_controller_test.rb
test "should get about" do
  get :about
  assert_response :success
end
          

变绿

  • config/routes.rb
  • app/controllers/static_pages_controller.rb
  • app/views/static_pages/about.html.erb

布局文件


$ mv app/views/layouts/application.html.erb layout_file

测试标题


assert_select "title", "Home | Ruby on Rails Tutorial Sample App"

有点动态内容的页面


<html>
<head>
  <title>Home | Ruby on Rails Tutorial Sample App</title>
</head>
<body>
  <h1>Sample App</h1>
  <p>
    This is the home page for the
    <a href="http://www.railstutorial.org/">Ruby on Rails Tutorial</a>
    sample application.
  </p>
</body>
</html>
          

DRY

  • DRY (Don’t Repeat Yourself)
  • 布局和嵌入式 Ruby(重构)

ERB


<% 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="http://www.railstutorial.org/">Ruby on Rails Tutorial</a>
    sample application.
    </p>
</body>
</html>
          

布局文件


$ mv layout_file app/views/layouts/application.html.erb

<!DOCTYPE html>
<html>
<head>
  <title><%= yield(:title) %> | Ruby on Rails Tutorial Sample App</title>
  <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %>
  <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
  <%= csrf_meta_tags %>
</head>
<body>
  <%= yield %>
</body>
</html>

课后练习

  • 去除测试代码里面的重复代码
  • 添加一个“联系”页面和测试代码

Q & A

下一课