当我想测试我的助手类时,无法在ActionView :: TestCase中使用flash

时间:2010-10-27 08:26:56

标签: ruby-on-rails ruby unit-testing testing tdd

我想在我的帮助器类中测试一个方法,但是当我执行类似的操作时:

require 'test_helper'

class ApplicationHelperTest < ActionView::TestCase
  def test_flash_messages
    flash[:notice] = "Hello World"
    assert_equal "<div class=\"message-notice\">Hello World<\/div>", flash_messages
  end
end

比我得到的“NoMethodError:未定义的方法`flash'为nil:NilClass”

但是当我做的事情如下:

flash = {}
flash[:notice] = "Hello World"
assert_equal "<div class=\"message-notify\">Hello World<\/div>", flash_messages

我收到相同的错误消息但在“application_helper.rb:6:in`flash_messages'”中调用

顺便说一句,我的application_helper看起来像是:

module ApplicationHelper

  def flash_messages
    fl = ''
    flash.each do |key,msg|
      if flash[key]
        fl = fl + "<div class=\"message-#{key}\">#{msg}</div>"
      end
      flash[key] = nil
    end
    return fl
  end

end

这适用于网站,但我希望能够通过单元测试来测试这种方法。

2 个答案:

答案 0 :(得分:0)

只需将flash方法定义为测试中的存根:

class ApplicationHelperTest < ActionView::TestCase
  def flash
    @flash ||= {}
  end

  def test_flash_messages
    flash[:notice] = "Hello World"
    assert_equal "<div class=\"message-notice\">Hello World<\/div>", flash_messages
  end
end

答案 1 :(得分:-1)

您只能在控制器中使用flash[:notice]来设置它们,并在视图中使用它们来渲染它们。 Flash在ActionController::Flash中声明。

当您创建自己的Flash Hash(flash = {})时,它可以正常工作,但该Flash变量不会以任何方式提供给您的助手,因此再次出现错误。

如果您想正确测试您的Flash消息,我建议您使用像Cucumber这样的工具编写测试:执行操作,并期望在HTML响应中看到一些文本。效果很好。