2

给定以下 RSpec 测试:

  context "items" do
    it "should be able to place links in an expandable menu" do
      output = helper.button("Hello", '#') do
        self.content << helper.item("Test", "example.org")
      end.should include "Test"
    end
  end

以及以下助手:

 def button(name, url, options = {}, &block)
    if block_given?
      content = with_output_buffer(&block)
      content_tag(:li, :class => 'expandable menu-item') do
        concat link_to(content_tag(:span, name), url, options)
        concat content_tag :div, content, :class => :box
      end
    else
      return content_tag :li, link_to(content_tag(:span, name), url, options), :class => :button
    end
  end

如果给按钮助手一个块,则该助手应该在单击后创建一个按钮和一个可扩展菜单。

示例视图:

= menu do
  = button("Test", '#') do
    %h1 Hello you!

产生:

<li class="expandable menu-item"><a href="#"><span>Test</span></a><div class="box"><h1>Hello you!</h1> 

正是我所期望的!一旦我尝试了 RSpec 测试,它就会失败,经过进一步检查,似乎在

<div class="box">...</div>

RSpec 输出:

expected "<li class=\"expandable menu-item\"><a href=\"#\"><span>Hello</span></a><div class=\"box\"></div></li>" to include "Test"

我试过在 if block_given 中提升内容?在 content = with_output_buffer(&block) 之后,它确实是空的。我在测试中一定做错了什么,为什么它是空的。

帮助将不胜感激!:)

4

1 回答 1

4

好,我会试试 :-)

你有什么特别的理由使用with_output_buffer而不是capture吗?

您可以查看capture源代码:..../gems/actionpack-3.0.3/lib/action_view/helpers/capture_helper.rb您会发现它的使用with_output_buffer方式与您使用它的方式不同。

要点是capture可以使用返回字符串的块。因此,您可以简单地使用:

it "should work" do
  helper.button("Hello", "#") do
    "test"
  end.should include "test"
end

更新:啊,我忘了提到当您更改代码时它会起作用:

content = with_output_buffer(&block)

content = capture(&block)
于 2011-01-11T10:36:59.367 回答