Uninitialized Constant when adding helper module to Model Test

1.4k views Asked by At

I'm trying to do something fairly simple - add a module with helper methods to a Model test, but I keep getting the following error

uninitialized constant NeighborhoodTest::NeighboorhoodTestHelper

The module is located in test/helpers/neighborhood_test_helper.rb

module NeighborhoodTestHelper

  def create_polygon
    points = self.geolocate
    boundary = Geokit::Polygon.new(points)
  end
   .
   .
end

Per the recommendation in this SO answer, did the following inside test/models/neighborhood_test.rb:

require 'test_helper'
require 'helpers/neighborhood_test_helper'


class NeighborhoodTest < ActiveSupport::TestCase
  include NeighboorhoodTestHelper

  def setup
    @crime = crimes(:arrest)
    @neighborhood = neighborhoods(:one)
  end

   test "neighborhood should contain crime" do
     neighborhood_boundary = @neighborhood.create_polygon
     crime_location = @crime.geolocate
     assert neighborhood_boundary.contains?(crime_location)
   end
end

I also tried this SO that didn't work. Anyone know why this approach doesnt work in Models?

2

There are 2 answers

0
RamPrasad Reddy On

tests/some_helper.rb

module SomeHelper
  def method1
    -----------
    -----------
  end

  def method2
    -----------
    -----------
  end
end

tests/test_helper.rb

require some_helper.rb

You can now access method1 and method2 in any of your test cases. Hope it helps you .

0
DBrown On

I ran into this today with rspec 3.8, and with other helper tests working just fine, I was very curious to know what made this one spec so special.

In my case, it turned out the spec file name, for whatever reason, was given the same file name as the helper module itself. When trying to load the constant it was looking in the spec file, since it had taken the place of "my_helper" and in turn ignoring the actual module. Adding a _spec at the end of the spec file name allowed this error to go away, and that spec ran as intended after.

I know this is a simple issue, but if you have hundreds upon hundreds of spec files, you may not be constantly looking at the file names.