代码之家  ›  专栏  ›  技术社区  ›  davideghz

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

  •  0
  • davideghz  · 技术社区  · 10 年前

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

    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
    

    路线.rb

    Rails.application.routes.draw do
    
      root 'static_pages#home'
    
      get 'static_pages/help'
      get 'static_pages/about'
      get 'static_pages/contact'
    
    end
    

    联系人.html erb

    <% provide(:title, "Contact")%>
    
    <h1>Help</h1>
    <p>
      Some text.
    </p>
    

    应用程序.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 回复  |  直到 10 年前
        1
  •  0
  •   Simone Carletti    10 年前

    不管是好是坏,这是Rails作为传统配置方法的一部分所公开的各种“特性”之一。根据我的经验,这个特定的功能主要是一个不必要的副作用。

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

    在您的案例中,因为您创建了 contact.html.erb 模板,您创建了一条与 #contact 动作,这等同于同一个控制器

    class StaticPagesController < ApplicationController
      def home
      end
    
      def help
      end
    
      def about
      end
    
      def contact
      end
    end