【问题标题】:Rails testing render action in controllerRails 在控制器中测试渲染动作
【发布时间】:2018-02-28 21:53:49
【问题描述】:

我有一个动态驱动的 Rails 应用程序,其中视图由请求的路径决定。

routes.rb:

Rails.application.routes.draw do
  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html

  get ':tenant', to: 'tenants#home'
  get  '/:path', to: 'tenants#page', :constraints => { :path => /.*/ }
end

租户控制器:

class TenantsController < ApplicationController
    def home
        render :template => params[:tenant] + "/home"
    end

    def page
        render :template => params[:path]
    end
end

如您所见,我们从端点获取路径约束并从中渲染视图模板。

我想编写一个测试来确保 rails 请求一个与请求的 URL 匹配的视图模板。 (基本上是测试 TenantsController 中的 page 方法)。

鉴于我不想将我的测试绑定到系统中可能存在的租户,如果测试不知道某些 Tennant,我一般如何为此编写测试?

【问题讨论】:

    标签: ruby-on-rails ruby


    【解决方案1】:

    您可以使用assert_template 方法为您的控制器编写测试:

    test "should render the correct template" do
      ['path1', 'path2'].each do |path|
        get '/', params: { path: path }
        assert_template "#{path}"
      end
    end
    

    This guide 提供有关如何测试控制器的更多详细信息。

    【讨论】:

      猜你喜欢
      • 2016-11-16
      • 1970-01-01
      • 1970-01-01
      • 2011-08-28
      • 1970-01-01
      • 2014-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多