ruby on rails - Mock a class's local method -
i trying write test case in rpec class this
class abc def method_1( arg ) #does , return value based on arg end def initialize @service = method_1( arg ) end def getsomething_1 return @service.get_seomthing_1 end def getsomething_2 return @service.get_seomthing_2 end end
now want initiate @service instance variable mocked object can use mocked object return values against can validate unit tests.
i tried like
describe abc before(:each) myobject = double() myobject.stub(:get_something_1).and_return("somevalue") abc.any_instance.stub(:method_1).and_return(myobject) end "checks correctness of getsomething_1 method of class abc" @abc = abc.new @abc.getsomething_1.should eql("somevalue") end end
now when trying run test @service not getting initialized object want to. seems method_1 not getting mocked behaviour defined. can how assign @service mocked object.
the problem you're having you're stubbing :method_1
, allows control returns, while short-circuiting behaviour. unfortunately, method_1
returns irrelevant, it's does—assigning @service
—that's interesting.
without seeing actual interface , design of class, can't suggest improvements on score, can @ least expectation work correctly substituting references instance variable (ie. @service.some_method
) attr_reader:
class abc attr_reader :service # ... def getsomething_1 return service.get_seomthing_1 end end
and in spec:
describe abc # .. before abc.any_instance(:service).and_return(myobject) # ... end "checks correctness of getsomething_1 method of class abc" @abc = abc.new("xyz") @abc.getsomething_1.should eql("somevalue") end end
in case, instance of abc
return mock when attribute service
called, allowing getsomething_1
correctly reference mock.
Comments
Post a Comment