Stub require statement in rspec?

1.6k Views Asked by At

I have to maintain a Ruby script, which requires some libs I don't have locally and which won't work in my environment. Nevertheless I want to spec some methods in this script so that I can change them easily.

Is there an option to stub some of the require statements in the script I want to test so that it can be loaded by rspec and the spec can be executed within my environment?

Example (old_script.rb):

require "incompatible_lib"
class Script
  def some_other_stuff
    ...
  end
  def add(a,b)
    a+b
  end
end

How can I write a test to check the add function without splitting the "old_Script.rb" file and without providing the incompatible_lib I don't have?

2

There are 2 best solutions below

0
On BEST ANSWER

Thanks, I also thought about the option of adding the files, but finally hacked the require itself within the test case:

module Kernel
  alias :old_require :require
  def require(path)
    old_require(path) unless LIBS_TO_SKIP.include?(path)
  end
end

I know that this is an ugly hack but as this is legacy code executed on a modified ruby compiler I can't easily get these libs running and it's sufficient to let me test my modifications...

0
On

Instead of stubbing require which is "inherited" from Kernel, you could do this:

  1. Create a dummy incompatible_lib.rb file somewhere that is not in your $LOAD_PATH. I.e., if this is a Ruby application (not Rails), don't put it in lib/ nor spec/.
  2. You can do this a number of ways, but I'll tell you one method: in your spec file which tests Script, modify $LOAD_PATH to include the parent directory of your dummy incompatible_lib.rb.
  3. Ordering is very important -- next you will include script.rb (the file which defines Script).

This will get you around the issue and allow you test test the add method.

Once you've successfully tested Script, I would highly recommend refactoring it so that you don't have to do this technique, which is a hack, IMHO.