views:

16

answers:

1

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.

A: 

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.

Ariejan
Thaks for the answer. Sad ... If I had know that the standard testing platform is not capable to test any kind of on coming issues, I would have chosen an other platform ...
vurte
I believe there are view tests with a default rails install. You can you could test the flash there as well.
Ariejan