3

我正在尝试测试 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

使用以下堆栈跟踪:

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'

请建议我做错了什么?

谢谢。

4

1 回答 1

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 字符串,但并非在所有情况下都有用。

于 2009-09-26T10:02:30.680 回答