使用RSpec和Haml测试嵌套布局助手

Sas*_*oss 5 ruby haml rspec ruby-on-rails

在ApplicationHelper中我有这样的代码:

def inside_layout layout = 'application', &block
  @template.instance_variable_set '@content_for_layout', capture(&block)
  concat \
    @template.render :file => "layouts/#{layout}", :use_full_path => true
end
Run Code Online (Sandbox Code Playgroud)

其行为如下:

application.html.haml:

!!!
%html
  %head
    ...
  %body
    = yield
Run Code Online (Sandbox Code Playgroud)

common_pages.html.haml:

- inside_layout do
  ...
Run Code Online (Sandbox Code Playgroud)

然后,common_pages布局在应用程序布局中呈现.

我如何用RSpec测试这个助手?

当我从spec文件中调用inside_layout时:

helper.inside_layout { }
Run Code Online (Sandbox Code Playgroud)

RSpec说错误:

ActionView::MissingTemplate in 'ApplicationHelper inside_layout should render nested layout within application layout'
Missing layout layouts/application.erb in view path
Run Code Online (Sandbox Code Playgroud)

但应用程序运行正常.

rud*_*rud 3

您不能在辅助程序的 rspec 中直接使用渲染调用,因为未在该上下文中设置视图路径。

建议:

  • 使用模拟进行渲染调用。
  • 更改您的代码,并将渲染调用移到视图模板中,然后仅从 inside_layout 方法返回渲染调用的参数。

阅读更多: http: //pivotallabs.com/users/john/blog/articles/854-friday-5-11-standup-view-paths-in-rspec-helper-tests-write-attribute-for-type-in ​​ference -