开发者

Can't use flash in ActionView::TestCase when I want to test my helper class

I wanted to test a method in my helper class but when I do something like:

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

than I get "NoMethodError: undefined method `flash' for nil:NilClass"

But when I do something like:

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

I get the same error message but it is called in "application_helper.rb:6:in `flash_messages'"

By the way my application_helper looks like:

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

This works on the website, but I want to be able to test this kind of method with unit test.


Just define a flash method as a stub in your test:

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


You can only use flash[:notice] in your controllers to set them, and in your views to render them. The Flash is declared in ActionController::Flash.

When you create your own Flash Hash (flash = {}), it works okay, but that flash variable is not made available to your helper in any way, hence the error again.

If you want to test your flash messages correctly, I suggest you write test with a tool like Cucumber: Perform an action, and expect to see some text in the HTML response. Works great.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜