Rails: I can't call a function in a module in /lib - what am I doing wrong?

前端 未结 9 1775
鱼传尺愫
鱼传尺愫 2021-01-31 08:08

I know I\'m doing something stupid or failing to do something intelligent - I\'m frequently guilty of both.

Here\'s an example of what\'s causing me pain:

I have

9条回答
  •  南笙
    南笙 (楼主)
    2021-01-31 08:20

    I messed with this for a while and learned several things. Hopefully this will help someone else out. I am running Rails 3.2.8.

    My module (utilities.rb) looks like this and is in the /lib directory of my rails app:

    module Utilities
    
      def compute_hello(input_string)
         return "Hello #{input_string}"
      end
    
    end
    

    My test (my_test.rb) looks like this and is in the /test/unit directory of my rails app:

    require "test_helper"
    require "utilities"
    
    class MyTest < ActiveSupport::TestCase
      include Utilities
    
      def test_compute_hello
        x = compute_hello(input_string="Miles")
        print x
        assert x=="Hello Miles", "Incorrect Response"
      end
    
    end
    

    Here are a few things to note: My test extends ActiveSupport::TestCase. This is important because ActiveSupport adds /lib to the $LOAD_PATH. (seehttp://stackoverflow.com/questions/1073076/rails-lib-modules-and)

    Secondly, I needed to both "require" my module file, and also "include" the module. Lastly, it is important to note that the stuff that gets included from the module essentially gets placed in the test class. So... be careful that the module that you include doesn't start with "test_". Otherwise, Rails will attempt to run your module method as a test.

提交回复
热议问题