Write stub to rspec?
I need to maintain a Ruby script that requires some libraries that I don't have locally and that won't work in my environment. However, I want to specify some methods in this script so that I can change them easily.
Is there a way to stub out some of the statements require
in the script that I want to test so that it can be rspec loaded and the spec can be executed in 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 test a function add
without splitting the old_Script.rb file and without giving incompatible_lib
me one?
source to share
Thanks, I also thought about adding files, but finally hacked the request itself in 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 this is an ugly hack, but since this is legacy code executed on a modified ruby ββcompiler, I cannot easily run these libraries, and this is enough to let me check my modifications ...
source to share
Instead of stubbing require
, which is "inherited" from Kernel
, you can do this:
- Create a dummy file
incompatible_lib.rb
somewhere that is not in your $ LOAD_PATH. If it's a Ruby (not Rails) application, don't put it inlib/
andspec/
. - You can do this in a number of ways, but I will tell you one method: in your spec file that checks
Script
, change $ LOAD_PATH to include the parent directory of your dummy t22>. - The order is very important - in the future you will include
script.rb
(the file that definesScript
).
This will cause a problem and allow you to test the method add
.
Once you've successfully tested it Script
, I highly recommend refactoring it so that you don't have to do this technique, which is a hack, IMHO.
source to share