【问题标题】:output_buffer is null on helper spec辅助规范上的 output_buffer 为空
【发布时间】:2009-09-25 09:31:18
【问题描述】:

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

请指出我做错了什么?

谢谢。

【问题讨论】:

    标签: ruby-on-rails unit-testing rspec helper


    【解决方案1】:

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

    【讨论】:

    • 在更高版本的 rspec 中,#eval_erb 方法似乎已被弃用
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-24
    • 2016-10-24
    • 2020-01-27
    • 2015-12-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多