Rails - 控制器中没有任何动作,但我一直通过测试。为什么?
Rails - no action in controller, but I keep passing test. Why?
我编写了一个基本测试来确保页面和标题按预期呈现。
static_pages_controller_test.rb
require 'test_helper'
class StaticPagesControllerTest < ActionController::TestCase
test "should_get_contact" do
get :contact
assert_response :success
assert_select "title", "Contact"
end
end
routes.rb
Rails.application.routes.draw do
root 'static_pages#home'
get 'static_pages/help'
get 'static_pages/about'
get 'static_pages/contact'
end
contact.html.erb
<% provide(:title, "Contact")%>
<h1>Help</h1>
<p>
Some text.
</p>
application.html.erb
<!DOCTYPE html>
<html>
<head>
<title><%= yield(:title) %></title>
...
</head>
<body>
<%= render 'layouts/header' %>
<div class="container">
<%= yield %>
<%= render 'layouts/footer' %>
</div>
</body>
</html>
这是我的 static_pages_controller.rb
class StaticPagesController < ApplicationController
def home
end
def help
end
def about
end
end
如您所见,没有 "contact" 操作,所以我预计测试不会通过,而我一直在亮绿灯。
davide@davidell:~/Desktop/app/sample_app$ bundle exec rake test
Run options: --seed 62452
# Running:
....
Finished in 0.194772s, 20.5369 runs/s, 41.0737 assertions/s.
4 runs, 8 assertions, 0 failures, 0 errors, 0 skips
为什么?我错过了什么?非常感谢您的回答,祝新年快乐:)
无论好坏,这是 Rails 作为约定优于配置方法的一部分公开的各种 "features" 之一。根据我的经验,此特定功能主要是不需要的副作用。
如果您的请求与路由匹配,并且该路由有一个与控制器和请求格式匹配的模板,那么 Rails 将假装该操作被定义为控制器中的一个简单的空方法。
在你的例子中,因为你创建了 contact.html.erb
模板并且你创建了一个匹配 #contact
动作的路由,这相当于同一个控制器
class StaticPagesController < ApplicationController
def home
end
def help
end
def about
end
def contact
end
end
我编写了一个基本测试来确保页面和标题按预期呈现。
static_pages_controller_test.rb
require 'test_helper'
class StaticPagesControllerTest < ActionController::TestCase
test "should_get_contact" do
get :contact
assert_response :success
assert_select "title", "Contact"
end
end
routes.rb
Rails.application.routes.draw do
root 'static_pages#home'
get 'static_pages/help'
get 'static_pages/about'
get 'static_pages/contact'
end
contact.html.erb
<% provide(:title, "Contact")%>
<h1>Help</h1>
<p>
Some text.
</p>
application.html.erb
<!DOCTYPE html>
<html>
<head>
<title><%= yield(:title) %></title>
...
</head>
<body>
<%= render 'layouts/header' %>
<div class="container">
<%= yield %>
<%= render 'layouts/footer' %>
</div>
</body>
</html>
这是我的 static_pages_controller.rb
class StaticPagesController < ApplicationController
def home
end
def help
end
def about
end
end
如您所见,没有 "contact" 操作,所以我预计测试不会通过,而我一直在亮绿灯。
davide@davidell:~/Desktop/app/sample_app$ bundle exec rake test
Run options: --seed 62452
# Running:
....
Finished in 0.194772s, 20.5369 runs/s, 41.0737 assertions/s.
4 runs, 8 assertions, 0 failures, 0 errors, 0 skips
为什么?我错过了什么?非常感谢您的回答,祝新年快乐:)
无论好坏,这是 Rails 作为约定优于配置方法的一部分公开的各种 "features" 之一。根据我的经验,此特定功能主要是不需要的副作用。
如果您的请求与路由匹配,并且该路由有一个与控制器和请求格式匹配的模板,那么 Rails 将假装该操作被定义为控制器中的一个简单的空方法。
在你的例子中,因为你创建了 contact.html.erb
模板并且你创建了一个匹配 #contact
动作的路由,这相当于同一个控制器
class StaticPagesController < ApplicationController
def home
end
def help
end
def about
end
def contact
end
end