output_buffer is null on helper spec
-
16-09-2019 - |
Question
I am trying to test the html block method inside the rails helper:
def dashboard_widget(header, &proc)
concat('<div class="dashboard-widget">')
etc
end
The code works perfectly in the development environment, but the following test is failed:
it "should be created" do
helper.dashboard_widget('My widget') do
"hello world"
end.should be_true
end
With the following 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'
Please, suggest what am I doing wrong?
Thanks.
Solution
There's an RSpec method for testing helpers that concatenate output instead of returning it:
output = eval_erb("<% helper.dashboard_widget('My widget') { 'hello world' } %>")
output.should be_happy # meaningful statement goes here
This is the best way to approach blocks which will have HTML from your views:
output = eval_erb <<-HTML
<% helper.dashboard_widget('My widget') do %>
<h1>Widget</h1>
<p>Hello World, this is my cool widget</p>
<% end %>
HTML
However, I've found a cleaner way for testing helpers that use concatenate, but don't use HTML within the block:
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
Saves the need of having ERB strings built in the spec, but not useful in all situations.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow