[rspec-users] Mock Global method

garren
Fri, 26 Mar 2010 11:19:02 -0000

Perfect thanks for that.

On Mar 25, 4:29?pm, David Chelimsky <dchelim... at gmail.com>
wrote:
> On Mar 25, 2010, at 8:44 AM, garren wrote:
>
> > I''m actually looking to mock "my_helper_method"
here. Or to be more
> > general any method that is created outside of a class.
>
> When you create a method outside a class, it is available on every object:
>
> def foo
> ? "foo"
> end
>
> class Bar
> end
>
> describe Bar do
> ? it "responds to foo" do
> ? ? Bar.new.foo.should == "foo"
> ? end
> end
>
> In terms of mocking or stubbing that, just do it directly on the object.
>
> describe Widget do
> ? it "does something" do
> ? ? widget = Widget.new
> ? ? widget.stub(:some_method_i_defined_outside_a_class) { "this
value" }
> ? ? # ...
> ? end
> end
>
> HTH,
> David
>
> PS, if you''re mocking or stubbing a method, it doesn''t
need to actually exist.
>
>
>
> > On Mar 25, 6:27 am, "J. B. Rainsberger" <jbrainsber... at
gmail.com>
> > wrote:
> >> garren wrote:
> >>> I''m very new to ruby and mocking a dynamic language.
I would like to
> >>> mock a helper method in Sinatra. So an example is this:
>
> >>> ? ? helper do
> >>> ? ? ?def my_helper_method
> >>> ? ? ? ?puts "Should do something useful here..."
> >>> ? ? ?end
> >>> ? ?end
>
> >>> How would I mock that method and how would I mock a method in
general
> >>> that is a global method. Is it better practice not to have
global
> >>> methods? Should I rather have an object inside the method call
that
> >>> does all the work and I can mock that?
>
> >> You can probably set an expectation on Kernel#puts, since although
#puts
> >> looks global, it belongs to Kernel.
>
> >> As for whether you should use #puts directly here, or indirectly
through
> >> another object that you can easily control, that depends on the
> >> situation. Try both and compare the results.
>
> >> In your situation, I''d probably just set expectations on
Kernel#puts
> >> until that caused me problems, at which point I''d
separate the behavior
> >> of deciding what to print from deciding where to print it. I find
> >> formatting messages much easier to check, in general, than
displaying them.
>
> >> Have fun.
> >> --
> >> J. B. Rainsberger
::http://www.jbrains.ca::http://www.thecodewhisperer.com
> >> _______________________________________________
> >> rspec-users mailing list
> >> rspec-us... at
rubyforge.orghttp://rubyforge.org/mailman/listinfo/rspec-users
> > _______________________________________________
> > rspec-users mailing list
> > rspec-us... at rubyforge.org
> >http://rubyforge.org/mailman/listinfo/rspec-users
>
> _______________________________________________
> rspec-users mailing list
> rspec-us... at