【问题标题】:Can't use flash in ActionView::TestCase when I want to test my helper class当我想测试我的助手类时,不能在 ActionView::TestCase 中使用 flash
【发布时间】:2010-10-27 08:26:56
【问题描述】:

我想在我的助手类中测试一个方法,但是当我执行以下操作时:

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: undefined method `flash' for 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

这在网站上有效,但我希望能够通过单元测试来测试这种方法。

【问题讨论】:

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


    【解决方案1】:

    只需将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
    

    【讨论】:

      【解决方案2】:

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

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

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

      【讨论】:

      • 感谢您的回答。伤心...如果我知道标准测试平台无法测试任何即将出现的问题,我会选择其他平台...
      • 我相信有默认安装导轨的视图测试。你也可以在那里测试闪光灯。
      • 这个建议并不完全正确。您绝对可以存根 flash 方法来完成原始问题的目标。
      猜你喜欢
      • 1970-01-01
      • 2021-05-03
      • 1970-01-01
      • 2016-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多