【问题标题】:How do I test whether my controller rendered the right layout on Rails 3?如何测试我的控制器是否在 Rails 3 上呈现了正确的布局?
【发布时间】:2011-06-27 01:45:22
【问题描述】:

控制器代码:

class BooksController < ApplicationController
  def index
    @books = Book.all
    respond_to do |format|
      format.html do
        render 'index', :layout => 'topgun'
      end
    end
  end
end

我应该如何在规范中对此进行测试?

require 'spec_helper'

describe BooksController do
  describe "GET index" do
    it "renders the topgun layout" do
      get :index
      # ???
    end
  end
end

我检查了this related post,但我的response 对象似乎没有layout 属性/方法。

【问题讨论】:

    标签: ruby-on-rails rspec


    【解决方案1】:

    您可能会发现"Testing Controllers with RSpec" RailsCast 和官方rspec-rails documentation 很有帮助。

    查看assert_template 的代码(这正是render_template 所调用的),看起来您应该能够做到

    response.should render_template("index")
    response.should render_template(:layout => "topgun")
    

    虽然我不完全确定这会奏效。

    【讨论】:

    • 我在assert_template rails.rubyonrails.org/classes/ActionController/Assertions/… 的官方文档/源代码中没有看到 :layout 选项
    • 如果你查看它的来源,有一个案例if options.key?(:layout)。但是现在我仔细看了一下,可能还必须声明 :partial 键以检查是否有布局键。此外,您似乎正在查看旧的 rails 文档,我正在查看 api.rubyonrails.org 上的 3.0 文档
    • 我们必须查看不同的代码/页面 :) 我链接的那个没有 :layout 键。它们过时了吗?
    • 是的,我认为您正在查看的是 2.3,3.0 文档位于 api.rubyonrails.org。不幸的是,布局键仍然隐藏在文档的源代码中,而不是示例的一部分。
    • 仅供参考,我无法测试控制器是否呈现布局 。无论控制器操作做什么,expect(response).to render_template(layout: nil) 总是通过。 RSpec 2.13.0,Rails 3.2.13。
    【解决方案2】:

    对于 RSpec 3:

    expect(response).to render_template(:new)   # wraps assert_template
    

    https://relishapp.com/rspec/rspec-rails/v/3-7/docs/controller-specs

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-27
      • 1970-01-01
      • 1970-01-01
      • 2016-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多