【问题标题】:Rspec testing layoutRspec 测试布局
【发布时间】:2010-12-12 23:19:15
【问题描述】:

如何测试 RSpec 中是否使用了特定布局?我试过 template.layout、response.layout 和 response.should render_template("layout") 都没有运气。

【问题讨论】:

    标签: testing layout rspec


    【解决方案1】:

    在 rspec 2 中,在控制器规范中,您使用了您猜到的 render_template,但您需要包含相对于视图目录的路径。因此,如果您的布局是 app/views/layouts/mylayout.html.erb,那么您的规范如下所示:

    response.should render_template "layouts/mylayout"
    

    【讨论】:

    • 你如何测试没有使用布局。例如,假设控制器确实“渲染:layout => false”。你如何测试它?
    【解决方案2】:

    RSpec 3 的更新语法:

    expect(response).to render_template(:index) # view
    expect(response).to render_template(layout: :application) # layout
    

    RSpec docs

    或者如果你更喜欢@Flov's one-liner,你可以写:

    expect(response).to render_template(:index, layout: :application)
    

    注意render_template 代表assert_template。你可以在这里找到这些文档:ActionController assert_template

    【讨论】:

    • 请注意,这不再有效,而且文档已经过时了。
    【解决方案3】:

    此外,您可以在 rspec-2 的单行中同时测试布局和动作渲染:

    response.should render_template(%w(layouts/application name_of_controller/edit))
    

    【讨论】:

      【解决方案4】:
      # rspec-rails-1.3.x for rails-2
      describe HomeController do
        describe "the home page" do
          it "should use the :home_page layout" do
            get :index
            response.layout.should == "layouts/home_page"
          end
        end
      end
      
      # rspec-2 for rails-3 
      describe "GET index" do
        it "renders the page within the 'application' layout" do
          get :index
          response.should render_template 'layouts/application' # layout
          response.should render_template 'index'               # view
        end
      end
      

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-09-11
      • 1970-01-01
      • 2011-05-09
      • 1970-01-01
      • 1970-01-01
      • 2015-05-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多