我正在尝试在rails helper中测试html块方法:
def dashboard_widget(header, &proc)
concat('<div class="dashboard-widget">')
etc
end
代码在开发环境中完美运行,但以下测试失败:
it "should be created" do
helper.dashboard_widget('My widget') do
"hello world"
end.should be_true
end
使用以下stacktrace:
d:/s/ruby/lib/ruby/gems/1.8/gems/actionpack-2.3.4/lib/action_view/helpers/text_helper.rb:32:in `concat'
D:/makabu/medved/winvest/master/app/helpers/dashboards_helper.rb:6:in `dashboard_widget'
./spec\helpers\dashboards_helper_spec.rb:13:
d:/s/ruby/lib/ruby/gems/1.8/gems/rspec-1.2.8/lib/spec/example/example_methods.rb:40:in `instance_eva
l'
d:/s/ruby/lib/ruby/gems/1.8/gems/rspec-1.2.8/lib/spec/example/example_methods.rb:40:in `execute'
请,建议我做错了什么?
感谢。
答案 0 :(得分:8)
有一种用于测试助手的RSpec方法,它连接输出而不是返回它:
output = eval_erb("<% helper.dashboard_widget('My widget') { 'hello world' } %>")
output.should be_happy # meaningful statement goes here
这是处理视图中包含HTML的块的最佳方法:
output = eval_erb <<-HTML
<% helper.dashboard_widget('My widget') do %>
<h1>Widget</h1>
<p>Hello World, this is my cool widget</p>
<% end %>
HTML
但是,我发现了一种更简洁的方法来测试使用连接的帮助程序,但是不要在块中使用HTML:
before :each do
helper.output_buffer = ''
end
it "should be awesome"
helper.dashboard_widget 'My widget' do
:awesome
end
helper.output_buffer.should match(/awesome/)
end
无需在规范中构建ERB字符串,但在所有情况下都无用。