writing tests for modules in the lib folder

I want to write unit tests for the module file I created and put it in the lib directory. In the test / unit folder, I created the file mylib_test.rb . In the file I need mylib. When I run rake test:units , it gives the error const_missing: uninitialized constant mylib::constantname . I think this is because it does not load the rail environment, since the constant is defined in one of the initializer files. I'm right? How do I make it work? What is the best way to write unit tests for modules?

I am using rails 3.1.3 and the model works fine when I run the application from both the terminal and the browser.

+4
source share
2 answers

Finally, I realized what happened. In my test files, I included my modules from the lib directory, instead of reopening the module and putting the test files into the module. After doing this rake test: the devices work fine. Test files should remain in the test/unit directory

0
source

I also came across this. There are (at least?) Two possible problems:

  • Your module is not in the startup path

See config/application.rb for this line:

 config.autoload_paths += %W(#{config.root}/extras) 

If he commented on this, uncomment him. This line will enable autoload for all files inside extras and all files in extras subdirectories. It's probably safer to move your modules to extras , but if you really want to leave them in lib , change the line:

 config.autoload_paths += %W(#{config.root}/extras #{config.root}/lib) 
  • Your module is in the startup path, but not named as Rails expects

(see the following: Rails 2.3.5: How to get the code inside lib / directory / file.rb? )

By convention, Rails wants your module name to match the directory hierarchy and file name. Thus, it is expected that the extras/mylib.rb will contain

 module Mylib # not MyLib or My_lib ... end 

This also works for subdirectories, so the extras/mydir/mylib.rb should contain:

 module Mydir module Mylib # or class Mylib ... end end 

This naming convention matches what Rails expects for controllers and models. The underscores in the file name are converted to the camelcase class / module name. It is expected that a file named my_lib.rb will contain module MyLib (but not Mylib ).

NOTE that autoload does not mean that the module automatically loads at startup; rather, it automatically loads upon first use. Therefore, even if you have code like puts "hi from mylib" at the top of your mylib.rb file, you will not see this print until your code uses Mylib .

Finally, if you really want your modules to load at startup, run a file called config/initializers/force_load_libraries.rb and put it there:

 Dir.glob("#{Rails.root}/extras/force_load/*.rb").each { |f| require f } 

Now put your libraries in extras/force_load and they should load when Rails starts.

0
source

Source: https://habr.com/ru/post/1386296/


All Articles