Telling rspec to not load files - ruby

I'm trying to add some commit hooks to my git repo. I want to leverage Rspec and create commit message specs that will run each time I commit. I have figured out how to run rspec outside of the 'spec' command, but I now have an interesting problem.
Here is my current code:
.git/hooks/commit-msg
#!/usr/bin/env ruby
require 'rubygems'
require 'spec/autorun'
message = File.read(ARGV[0])
describe "failing" do
it "should fail" do
true.should == false
end
end
This is throwing an error when it gets to the describe call. Basically, it thinks that the commit message it receives is the file to load and run the specs against. Here is the actually error
./.git/COMMIT_EDITMSG:1: undefined local variable or method `commit-message-here' for main:Object (NameError)
from /Users/roykolak/.gem/ruby/1.8/gems/rspec-1.3.0/lib/spec/runner/example_group_runner.rb:15:in `load'
from /Users/roykolak/.gem/ruby/1.8/gems/rspec-1.3.0/lib/spec/runner/example_group_runner.rb:15:in `load_files'
from /Users/roykolak/.gem/ruby/1.8/gems/rspec-1.3.0/lib/spec/runner/example_group_runner.rb:14:in `each'
from /Users/roykolak/.gem/ruby/1.8/gems/rspec-1.3.0/lib/spec/runner/example_group_runner.rb:14:in `load_files'
from /Users/roykolak/.gem/ruby/1.8/gems/rspec-1.3.0/lib/spec/runner/options.rb:133:in `run_examples'
from /Users/roykolak/.gem/ruby/1.8/gems/rspec-1.3.0/lib/spec/runner.rb:61:in `run'
from /Users/roykolak/.gem/ruby/1.8/gems/rspec-1.3.0/lib/spec/runner.rb:45:in `autorun'
from .git/hooks/commit-msg:12
I am looking for a way to tell rspec to not load files. I have a suspicion that I will need to create my own spec runner. I came to this conclusion after viewing these lines in rspec-1.3.0/lib/spec/runner/example_group_runner.rb
def load_files(files)
$KCODE = 'u' if RUBY_VERSION.to_f < 1.9
# It's important that loading files (or choosing not to) stays the
# responsibility of the ExampleGroupRunner. Some implementations (like)
# the one using DRb may choose *not* to load files, but instead tell
# someone else to do it over the wire.
files.each do |file|
load file
end
end
But, I would like some feedback before I do that. Any thoughts?

Do you even really need all the special stuff that RSpec provides (should and the various matchers) just to verify the contents of a single file? It really seems like overkill for the problem.
spec/autorun eventually calls Spec::Runner.autorun which parses ARGV as if it held normal arguments for a spec command line.
When you install a bare “spec” file as a Git hook,
it will get arguments that are appropriate for the whatever Git hook is being used,
not spec-style arguments (spec filenames/directories/patterns and spec options).
You might be able to hack around the problem like this:
# Save original ARGV, replace its elements with spec arguments
orig_argv = ARGV.dup
%w(--format nested).inject(ARGV.clear, :<<)
require 'rubygems'
require 'spec/autorun'
# rest of your code/spec
# NOTE: to refer to the Git hook arguments use orig_argv instead of ARGV

Related

Filter ruby warnings

I want to create a gem to filter warnings in Ruby, and I'd like to do this for "syntax" and "runtime" warnings. I am struggling to work out how its possible to filter the syntax level warnings (or if this possible)
For example, if I run the following script
# myscript.rb
#blah
with ruby -w myscript.rb
myscript.rb:1: warning: possibly useless use of a variable in void context
myscript.rb:1: warning: instance variable #blah not initialized
Now, imagine this is part of a larger project. I would like to filter out any warnings from myscript. How would I go about doing this? Runtime errors would be easy to filter using silence_warnings style code from ActiveSupport https://github.com/rails/rails/blob/3be9a34e78835a8dafc3438f60afb412613773b9/activesupport/lib/active_support/core_ext/kernel/reporting.rb
But I don't know how (or if it's possible) to hook into Rubys syntax level warnings, as it seems to be they'd be run before you have the chance to monkey patch anything. All I can think of is to wrap the ruby script in another process which will filter all the warnings. For example:
myfilterprogram ruby -w myscript.rb which would then catch anything printed to STDERR and filter accordingly.
You may not be able to monkey patch before the main file is read, but you can make your main file call subfiles after doing monkeypatching.
myruby (executable)
#!/usr/bin/env ruby
module Kernel
def warn *args
args # => captured warnings
end
end
load ARGV[0]
Usage is:
myruby foo.rb

Is there a way to force a required file to be reloaded in Ruby?

Yes, I know I can just use load instead of require. But that is not a good solution for my use case:
When the app boots, it requires a config file. Each environment has its own config. The config sets constants.
When the app boots, only one environment is required. However, during testing, it loads config files multiple times to make sure there are no syntax errors.
In the testing environment, the same config file may be loaded more than once. But I don't want to change the require to load because every time the a spec runs, it reloads the config. This should be done via require, because if the config has already been loaded, it raises already initialized constant warnings.
The cleanest solution I can see is to manually reset the require flag for the config file after any config spec.
Is there a way to do that in Ruby?
Edit: adding code.
When the app boots it calls the init file:
init.rb:
require "./config/environments/#{ ENV[ 'RACK_ENV' ]}.rb"
config/environments/test.rb:
APP_SETTING = :foo
config/environments/production.rb:
APP_SETTING = :bar
spec/models/config.rb: # It's not a model spec...
describe 'Config' do
specify do
load './config/environments/test.rb'
end
specify do
load './config/environments/production.rb'
end
Yes it can be done. You must know the path to the files that you want to reload. There is a special variable $LOADED_FEATURES which stores what has been loaded, and is used by require to decide whether to load a file when it is requested again.
Here I am assuming that the files you want to re-require all have the unique path /myapp/config/ in their name. But hopefully you can see that this would work for any rule about the path name you can code.
$LOADED_FEATURES.reject! { |path| path =~ /\/myapp\/config\// }
And that's it . . .
Some caveats:
require does not store or follow any kind of dependency tree, to know what it "should" have loaded. So you need to ensure the full chain of requires starting with the require command you run in the spec to re-load the config, and including everything you need to be loaded, is covered by the removed paths.
This will not unload class definitions or constants, but simply re-load the files. In fact that is literally what require does, it just calls load internally. So all the warning messages about re-defining constants will also need to be handled by un-defining the constants you expect to see defined in the files.
There is probably a design of your config and specs that avoids the need to do this.
if you really want to do this, here's one approach that doesn't leak into your test process. Fork a process for every config file you want to test, communicate the status back to the test process via IO.pipe and fail/succeed the test based on the result.
You can go as crazy as you want with the stuff you send down the pipe...
Here's some quick and dirty example to show you what I mean.
a config
# foo.rb
FOO = "from foo"
another config
# bar.rb
FOO = "from bar"
some faulty config
# witherror.rb
asdf
and your "test"
# yourtest.rb
def load_config(writer, config_file)
fork do
begin
require_relative config_file
writer.write "success: #{FOO}\n"
rescue
writer.write "fail: #{$!.message}\n"
end
writer.close
exit # maybe this is even enough to NOT make it run your other tests...
end
end
rd, writer = IO.pipe
load_config(writer, "foo.rb")
load_config(writer, "bar.rb")
load_config(writer, "witherror.rb")
writer.close
puts rd.read
puts rd.read
puts rd.read
puts FOO
The output is:
success: from foo
success: from bar
fail: undefined local variable or method `asdf' for main:Object
yourtest.rb:24:in `<main>': uninitialized constant FOO (NameError)
as you can see, the FOO constant doesn't leak into your test process etc.
Of course you're only through half way because there's more to it like, making sure only one process runs the test etc.
Frankly, I don't think this is a good idea, no matter what approach you chose because you'll open a can of worms and imho there's no really clean way to do this.

Stub require statement in rspec?

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?
Instead of stubbing require which is "inherited" from Kernel, you could do this:
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/.
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.
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.
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...

How to execute local functions using code from external file in ruby?

Can a require execute a locally defined function? I guess the easiest way to describe what I need is to show an example.
I'm using ruby 1.9.3, but solutions for 1.8 and 2.0 are also welcome.
I have a file main.rb as the following:
class Stuff
def self.do_stuff(x)
puts x
end
require_relative('./custom.rb')
do_stuff("y")
end
And also have a file custom.rb in the same folder, with the following content:
do_stuff("x")
Running main.rb, I have following output:
/home/fotanus/custom.rb:1:in `<top (required)>': undefined method `do_stuff' for main:Object (NoMethodError)
from main.rb:5:in `require_relative'
from main.rb:5:in `<class:Stuff>'
from main.rb:1:in `<main>'
Note that without the require, the output is y.
I'm not sure if it is the best solution but using eval should do the trick.
class Stuff
def self.do_stuff(x)
puts x
end
eval(File.read('./custom.rb'))
do_stuff("y")
end
The output will be:
pigueiras#pigueiras$ ruby stuff.rb
x
y
In C, #include literally drops the code as-is into the file. require in Ruby is different: it actually runs the code in the required file in its own scope. This is good, since otherwise we could break required code by redefining things before the require.
If you want to read in the contents of a script and evaluate it in the current context, there are methods for doing just that: File.read and eval.

How to get rspec-2 to give the full trace associated with a test failure?

Right now if I run my test suite using rake spec I get an error:
1) SegmentsController GET 'index' should work
Failure/Error: get 'index'
undefined method `locale' for #
# ./spec/controllers/segments_controller_spec.rb:14:
in `block (3 levels) in '
This is normal as I do have an error :)
The problem is that the trace isn't very helpful. I know it broke in segments_controller_spec.rb, line 14, but this is just where I call the test:
### segments_controller_spec.rb:14
get 'index'
I would prefer to have the actual line breaking and the complete trace, not the part in the spec folder.
Running with --trace doesn't help.
You must run rspec with -b option to see full backtraces
Another (easier) alternative is to edit the .rspec file, and add the backtrace option.
It should look somewhat like this:
--colour
--backtrace
That will give you the full backtrace.
Hope this helps.
This will also work:
# rails_helper.rb
RSpec.configure do |config|
config.full_backtrace = true
end
Another approach is to clear all backtrace exclusion patterns in spec_helper.rb. I like this solution most as I'm able to keep all RSpec settings in one place and get rid of .rspec file or explicit --backtrace in .travis.yml.
# spec_helper.rb
RSpec.configure do |config|
config.backtrace_exclusion_patterns = []
end
I don't know how to get the controller error to show up in rspec. Sometimes it shows up but I don't know what conditions cause it to show up. Here is a way to see the error fairly quickly though:
Open another terminal session and run:
tail -f log/test.log
Then go back to the terminal session and run just the spec that had the error:
bin/rspec -b spec/requests/posts/index_spec.rb
Go back to the tail of the log and you should see the error, hopefully without too much other stuff surrounding it (because you ran the failing test by itself).
One more option when all else fails is to just add a rescue block and print out the stack try or add a binding pry statement there and use show-stack.
rescue Exception => e
puts ""
puts e.backtrace
puts ""

Resources