从字符串编译ERB代码时出错

时间:2014-12-14 01:18:04

标签: ruby-on-rails rspec erb

我正在为我的视图助手(Rails 4.0)编写一些测试,并尝试在执行它的字符串中编译ERB代码。但是,为了简单起见,我使用rails中的常用方法形成帮助程序并收到相同的错误:

Failure/Error: ERB.new(template).result
SyntaxError:
  (erb):1: syntax error, unexpected ')'
  ...out.concat(( field_set_tag do ).to_s); _erbout.concat "\n\t\...
  ...                               ^
  (erb):4: syntax error, unexpected end-of-input, expecting ')'
  ; _erbout.force_encoding(__ENCODING__)
                                        ^

这是我正在执行的代码:

template = <<-TEMPLATE
<%= field_set_tag do %>
    Lorem Ipsum
<% end %>
TEMPLATE

ERB.new(template).result

我发现了使用<%代替<%=的一些建议,但这会导致Lorem Ipsum成为唯一输出。我也尝试过使用HAML而不是ERB,但结果却类似。

如何让我的模板在字符串中使用<fieldset>Lorem Ipsum</fieldset>帮助器输出field_set_for

1 个答案:

答案 0 :(得分:3)

“正常”Eruby不允许使用<%=的表达式使用Rails使用它们的方式。 Rails extends the Erubis Eruby handler to add support for them。您的测试只是直接使用Erb,因此无法获得此支持。

您需要确保加载此支持才能使其正常工作。我可以得到它:

ActionView::Template::Handlers::Erubis.new(template).evaluate(ActionView::Base.new)

我不知道这是不是最好的方法。检查RSpec文档,可能有更好的方法来测试这样的部分视图。