2009-09-25 11 views
3

我試圖測試軌道助手裏面的HTML塊的方法:output_buffer是幫手規格空

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' 

請,建議我究竟做錯了什麼?

謝謝。

回答

7

有測試傭工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字符串的需求,但在所有情況下都無用。