Created
March 11, 2012 19:23
-
-
Save Jacobkg/2017761 to your computer and use it in GitHub Desktop.
For when you want to stub class methods on a class that may or may not be loaded
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class SuperStubbedClass; end | |
class ClassStubber | |
def self.stub!(class_string) | |
classes = class_string.split('::') | |
parent_klass = Object | |
classes.each do |class_name| | |
define_if_not_already(class_name, parent_klass) | |
parent_klass = parent_klass.const_get(class_name) | |
end | |
end | |
def self.unstub!(class_string) | |
classes = class_string.split('::') | |
parent_klass = Object | |
classes.each do |class_name| | |
if we_defined_class(class_name, parent_klass) | |
parent_klass.send(:remove_const, class_name) | |
return #Only need to remove the highest class that we created (not its children) | |
end | |
parent_klass = parent_klass.const_get(class_name) | |
end | |
end | |
def self.define_if_not_already(class_name, parent_klass) | |
unless parent_klass.const_defined?(class_name) | |
parent_klass.const_set(class_name, Class.new(SuperStubbedClass)) | |
end | |
end | |
def self.we_defined_class(class_name, parent_klass) | |
constant = parent_klass.const_get(class_name) | |
return false unless constant.is_a? Class #It could be a module | |
constant.superclass == SuperStubbedClass | |
end | |
end | |
######### | |
# Usage # | |
######### | |
describe "Example" do | |
stub_class_if_missing("User") | |
it "compiles" do | |
user = stub | |
User.stub(:find).with(1).and_return(user) | |
User.find(1).should == user | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment