[英]How do you test Rails helpers which accepts a block with RSpec?
进行以下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"
我是否曾尝试在block_given中提高内容? 在content = with_output_buffer(&block)之后,它确实为空。 我在测试中必须做错什么,为什么它是空的。
帮助将不胜感激! :)
好,我会试试 :-)
您是否有任何特定的原因使用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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.