Friday, August 14, 2009

rails and unit tests

today i came across a case when i wanted to test some code that would eventually be running on the rails environment (a bj job) but didn't really have anything Rails-y other than logging via Rails.logger.debug etc.

i ended up creating a stub for the rails logger so that i could run this as a simple unit test case instead of a rails test case which take a helluva long time.

add a new file called 'rails_stub.rb' into your test folder. in that dump the following code-


module Rails
#rails stub
def Rails::logger
return Rails::Logger.new
end
class Rails::Logger
def debug string
log "DEBUG:\t"+string
end
def info string
log "INFO:\t"+string
end
private
def log string
# adding a prefix
print "RAILS_LOG:"+string
end
end
end


in the test case, just require rails.rb and you are set to go., running the test case from the command line will dump the logs onto the terminal.

exercise for the future- get this stub logger to be a littl emore fancy- supress by level etc.

Sunday, July 26, 2009

unit testing private methods in ruby

don't u just love this???


class Class
def publicize_methods
saved_private_instance_methods = self.private_instance_methods
self.class_eval { public *saved_private_instance_methods }
yield
self.class_eval { private *saved_private_instance_methods }
end
end

and to test the private method blah of a class Foo


class TestFoo &Test::Unit::TestCase
def test_blah
Foo.publicize_methods do
assert_not_nil Foo.blah
end
end
end


and thats it... :)