Rails - 在控制器中没有动作,但我继续通过测试。为什么?

时间:2015-12-31 12:27:34

标签: ruby-on-rails tdd

我写了一个基本测试,以确保页面和标题按预期呈现。

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

正如您所注意到的那样,没有“接触”动作,所以我希望测试不要通过,而我一直在开绿灯。

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

为什么呢?我错过了什么?非常感谢您的回答,祝新年快乐:)

1 个答案:

答案 0 :(得分:0)

无论好坏,这是各种&#34;功能之一&#34;作为约定优于配置方法的一部分,由Rails公开。根据我的经验,这个特定功能主要是一个不必要的副作用。

如果您的请求与路由匹配,并且该路由的模板与控制器和请求格式匹配,那么Rails将假定该操作在控制器中被定义为一个简单的空方法。

在您的情况下,因为您创建了contact.html.erb模板,并且您创建了与#contact操作匹配的路由,这相当于同一个控制器

class StaticPagesController < ApplicationController
  def home
  end

  def help
  end

  def about
  end

  def contact
  end
end