对于helper规范,output_buffer为null

Bog*_*iev 3 unit-testing rspec ruby-on-rails helper

我试图在rails helper中测试html块方法:

def dashboard_widget(header, &proc)
  concat('<div class="dashboard-widget">')
  etc
end
Run Code Online (Sandbox Code Playgroud)

代码在开发环境中完美运行,但以下测试失败:

it "should be created" do
  helper.dashboard_widget('My widget') do 
    "hello world" 
  end.should be_true
end
Run Code Online (Sandbox Code Playgroud)

使用以下堆栈跟踪:

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'
Run Code Online (Sandbox Code Playgroud)

请,建议我做错了什么?

谢谢.

pat*_*pat 8

有一个用于测试助手的RSpec方法,它连接输出而不是返回它:

output = eval_erb("<% helper.dashboard_widget('My widget') { 'hello world' } %>")
output.should be_happy # meaningful statement goes here
Run Code Online (Sandbox Code Playgroud)

这是从您的视图中获取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
Run Code Online (Sandbox Code Playgroud)

但是,我发现了一种更简洁的方法来测试使用连接的助手,但是不要在块中使用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
Run Code Online (Sandbox Code Playgroud)

节省了在规范中构建ERB字符串的需要,但在所有情况下都没有用.