views:

50

answers:

1

Here's my situation - I have a helper named LayoutHelper that I use to help me build my layout, and I'm trying to test the following method.

It has a method in LayoutHelper that looks similar to this:

def show_login_form?
  return false if @hide_login_form || logged_in?
  return true
end

I also have the following in my application.rb:

helper_method :logged_in?

def logged_in?
  return @logged_in_user.present?
end

And finally, my test file looks like this:

require File.dirname(__FILE__) + '/../../test_helper'                          

class LayoutHelperTest < ActionView::TestCase                                  

  def test_hide_login_form                                                     
    assert(show_login_form?)                                                   
    hide_login_form                                                            
    assert(!show_login_form?)                                                  
  end                                                                          

end

My problem now is that when I run this test, I get this:

NoMethodError: undefined method `logged_in?' for #<LayoutHelperTest:0xb7a7aca8>
app/helpers/layout_helper.rb:17:in `show_login_form?'
layout_helper_test.rb:12:in `test_hide_login_form'

I'm wondering if I'm doing this the correct Rails way, and if so, what I need to change in order to get this test to work.

A: 

I have to say, this stumped me at first - but I finally figured out what wasn't quite right.

Helpers are html generators, and should be built in a bubble - not knowing what's going on in sessions, controllers, etc. Your show_login_form? method isn't generating code, it's working with controller methods. It should be in application_controller.rb itself, and tested in controller tests.

Once you move it here, you should have no problem testing. Oh, and this might be a shorter, sweeter way to write the method itself:

def show_login_form?
  !(@hide_login_form || logged_in?)
end

I hope this helps. It certainly got me to research helper tests, which I've neglected until now.

Jaime Bellmyer