【问题标题】:Uninitialized Constant when adding helper module to Model Test将帮助模块添加到模型测试时未初始化的常量
【发布时间】:2017-01-04 01:58:48
【问题描述】:

我正在尝试做一些相当简单的事情 - 将一个带有帮助方法的模块添加到模型测试中,但我不断收到以下错误

未初始化的常量 NeighborhoodTest::NeighboorhoodTestHelper

该模块位于 test/helpers/neighborhood_test_helper.rb

module NeighborhoodTestHelper

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

根据this SO 回答中的建议,在 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

我也试过this 所以没用。有人知道为什么这种方法在模型中不起作用吗?

【问题讨论】:

    标签: ruby-on-rails testing activesupport


    【解决方案1】:

    tests/some_helper.rb

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

    tests/test_helper.rb

    require some_helper.rb
    

    您现在可以在任何测试用例中访问 method1 和 method2。希望对你有帮助。

    【讨论】:

      【解决方案2】:

      我今天在使用 rspec 3.8 时遇到了这个问题,并且其他辅助测试运行良好,我很想知道是什么让这个规范如此特别。

      在我的例子中,无论出于何种原因,spec 文件名被赋予了与帮助模块本身相同的文件名。当试图加载它在规范文件中查找的常量时,因为它已经取代了“my_helper”并且忽略了实际的模块。在规范文件名的末尾添加 _spec 可以消除此错误,并且该规范按预期运行。

      我知道这是一个简单的问题,但如果您有成百上千的规范文件,您可能不会经常查看文件名。

      【讨论】:

        猜你喜欢
        • 2011-05-26
        • 2014-02-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多