代码之家  ›  专栏  ›  技术社区  ›  Bogdan Gusiev

helper spec上的输出缓冲区为空

  •  3
  • Bogdan Gusiev  · 技术社区  · 15 年前

    我正在尝试在Rails帮助程序中测试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
    

    使用以下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'
    

    拜托,建议我做错什么了?

    谢谢。

    1 回复  |  直到 15 年前
        1
  •  8
  •   pat    15 年前

    有一个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
    

    但是,我发现了一种更清晰的方法来测试使用concatenate但不在块中使用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字符串的需要,但在所有情况下都不有用。