2010-12-12 108 views
12

如何测试RSpec中使用的特定布局?我试过template.layout,response.layout和response.should render_template(“layout”),但没有运气。Rspec测试布局

回答

17

在rspec的2,在控制器的规格,使用render_template,你猜到了,但你需要包括相对views目录的路径。所以,如果你的布局是应用程序/视图/布局/ mylayout.html.erb,你的规格如下所示:

response.should render_template "layouts/mylayout" 
+0

而你如何测试没有使用布局。假设控制器例如'render:layout => false'。你如何测试它? – 2012-11-11 06:56:19

1
# 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 
+1

https://gist.github.com/11080d61648aaee51840我在rspec 2,rails 3上。我得到了一个不赞成的response.layout和建议的template.layout错误。 – 2010-12-14 01:22:33

+0

我根据您的反馈更新了我的答案。 – 2010-12-15 15:11:51

5

此外,您还可以测试,布局和动作的渲染,在一个班轮在rspec的-2:

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

为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

+0

只是一个说明,这不再起作用,而且文件是野蛮过时的。 – Sebastialonso 2017-09-07 20:19:33