How to mock an instance method of an already mocked object?

前端 未结 2 1337
轮回少年
轮回少年 2021-01-13 22:18

I need to mock the following:

Class User
  def facebook
    #returns an instance of a facebook gem
  end
end

So in my User tests, to access

2条回答
  •  深忆病人
    2021-01-13 23:15

    You could try something like this :-

    user = Factory(:user)
    user.stubs(:facebook => stub(:me => stub(:info => {:name => "John Doe"})))
    

    If you really want to check that all these methods are called (which I suspect you don't), you could do the following :-

    user = Factory(:user)
    user.expects(:facebook => mock(:me => mock(:info => {:name => "John Doe"})))
    

    It's a bit more verbose, but it's usually worthwhile giving each mock object a name :-

    user = Factory(:user)
    user.stubs(:facebook => stub('facebook', :me => stub('me', :info => {:name => "John Doe"})))
    

    I hope that helps.

提交回复
热议问题