【发布时间】:2010-12-12 23:19:15
【问题描述】:
如何测试 RSpec 中是否使用了特定布局?我试过 template.layout、response.layout 和 response.should render_template("layout") 都没有运气。
【问题讨论】:
如何测试 RSpec 中是否使用了特定布局?我试过 template.layout、response.layout 和 response.should render_template("layout") 都没有运气。
【问题讨论】:
在 rspec 2 中,在控制器规范中,您使用了您猜到的 render_template,但您需要包含相对于视图目录的路径。因此,如果您的布局是 app/views/layouts/mylayout.html.erb,那么您的规范如下所示:
response.should render_template "layouts/mylayout"
【讨论】:
RSpec 3 的更新语法:
expect(response).to render_template(:index) # view
expect(response).to render_template(layout: :application) # layout
或者如果你更喜欢@Flov's one-liner,你可以写:
expect(response).to render_template(:index, layout: :application)
注意render_template 代表assert_template。你可以在这里找到这些文档:ActionController assert_template。
【讨论】:
此外,您可以在 rspec-2 的单行中同时测试布局和动作渲染:
response.should render_template(%w(layouts/application name_of_controller/edit))
【讨论】:
# 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
【讨论】: