用rspec测试lib文件夹的正确方法?
我有一个测试,试图测试位于lib文件夹中的类。
现在我在parser_spec.rb中执行此操作
require 'spec_helper' require 'parser' --> Because my class is /lib/parser.rb describe "parser" do it "needs a url to initialize" do expect { Parser.new }.to raise_error(ArgumentError) end end
包含所有lib文件的正确方法是什么,以便它们在rspec测试的范围内?
你做的方式 – require 'parser'
是推荐的方式。 RSpec将lib
放在$LOAD_PATH
这样就可以像你一样需要相对于它的文件了。
Try this require_relative "../../lib/parser.rb" or require 'lib/parser.rb'
rspec在运行时自动加载’spec / spec_helper.rb’,它还会自动将’lib’文件夹添加到它的LOAD_PATH中,这样就可以正确地看到并且需要’lib / parser.rb’。
为了避免像Ryan Bigg所说的lib
自动加载,你可以自动加载放置在app根目录中的自定义目录:
进入/your/config/application.rb你可以添加:
config.autoload_paths += %W(#{config.root}/my_stuff)
然后,你可以这样做:
require 'spec_helper' describe Parser do #your code... end
也许,您可以将您的类放在模块中以避免冲突:
class MyStuff::Parser #your code... end
然后,你可以这样做:
require 'spec_helper' describe MyStuff::Parser do #your code... end
只需将’lib’文件夹放入autoload_path即可。 例如,在application.rb中
config.autoload_paths += "#{Rails.root}/lib/"
然后你可以正常做到
require 'spec_helper' describe Parser do ... end