Created
March 25, 2011 22:53
-
-
Save ilkerde/887804 to your computer and use it in GitHub Desktop.
RSpec mocking of existing methods in Ruby?!?
This file contains hidden or 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 Foo | |
def bar(n) | |
return gin n | |
end | |
def gin(n) | |
return n+1 | |
end | |
end | |
This file contains hidden or 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
require 'Foo' | |
describe "Foo, bar" | |
it "uses gin" do | |
Foo.new.stub!(:gin).and_return(1) | |
Foo.new.bar(3).should == 1 | |
end | |
end |
Explanation: in Foo_spec.rb#5 you create an instance and prepare the stub. In #6 you instanciate another Foo that does not know anything about the stub declared above. Huh? Thus the .should == 1
fails.
Thanks indeed for your guidance.
As a beginner it was not obvious to me that i'd mock out an instance of the method of that class rather than the definition of the method of that class. Good to know. BTW, it worked out well, just finished my first ruby code kata:
https://github.com/ilkerde/CodeKatas/tree/master/KataFizzBuzz.RSpec ;-)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Try this:
Hint: you don't need the
return
in the methods of Foo.