Skip to content

Instantly share code, notes, and snippets.

@ilkerde
Created March 25, 2011 22:53
Show Gist options
  • Save ilkerde/887804 to your computer and use it in GitHub Desktop.
Save ilkerde/887804 to your computer and use it in GitHub Desktop.
RSpec mocking of existing methods in Ruby?!?
class Foo
def bar(n)
return gin n
end
def gin(n)
return n+1
end
end
require 'Foo'
describe "Foo, bar"
it "uses gin" do
Foo.new.stub!(:gin).and_return(1)
Foo.new.bar(3).should == 1
end
end
@mhoyer
Copy link

mhoyer commented Mar 25, 2011

Try this:

describe "Foo, bar" do
  it "uses gin" do
    foo = Foo.new
    foo.stub!(:gin).and_return(1)
    foo.bar(3).should == 1
  end
end

Hint: you don't need the return in the methods of Foo.

@mhoyer
Copy link

mhoyer commented Mar 25, 2011

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.

@ilkerde
Copy link
Author

ilkerde commented Mar 26, 2011

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