views:

166

answers:

2

What I want is a way of not having to 'require' the class under test in each spec file.

So hoping there is a means of setting the root of the source code under test and rspec automatically mapping my tests, or any other means of automatically mapping specs to ruby files.

In Rspec for rails this happens magically, but this is not a rails project and I can't find any useful information.

A: 

What you have to do is to redefine Object.const_missing.

Found this basic example, modify it to fit your needs (set the right path, etc.):

def Object.const_missing(name)
  @looked_for ||= {}
  str_name = name.to_s
  raise "Class not found: #{name}" if @looked_for[str_name]
  @looked_for[str_name] = 1
  file = str_name.downcase
  require file
  klass = const_get(name)
  return klass if klass
  raise "Class not found: #{name}"
end
giorgian
+3  A: 

I am assuming you have a lib folder and a spec folder within your project where you have code and specs respectively. Create a spec/spec_helper.rb and add

 # project_name/spec/spec_helper.rb
 $: << File.join(File.dirname(__FILE__), "/../lib") 
 require 'spec' 
 require 'main_file_within_lib_folder_that_requires_other_files'

Now within your individual spec files now you just need to add the following line like rails

 require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')
nas
and if you're adverse to requiring the spec_helper at the top of each spec file, you can run your specs withspec -r spec/spec_helper.rb (or modify your rake spec task to use that -r option)
Pete Hodgson
What about if you are using autotest?
nas