ruby-on-rails – Rails:如何模拟宝石,例如fb_graph

我正在使用gem fb_graph.我是rails的新手,我正试图弄清楚如何使用rspec模拟这个gem. (
https://github.com/nov/fb_graph)

我试图测试的代码是:

facebook_user = FbGraph::User.new('me', :access_token => access_token['credentials']['token']).fetch
return facebook_user.friends

我正在思考以下几点:

fb_graph = mock(FbGraph)
user = mock(FbGraph::User)
fb_graph.should_receive(:new).should_return(user)
user.should_receive(:fetch).should_return(fb_graph_user)
user.should_receive(:friends)

谢谢!

最佳答案 我不会模仿宝石的代码,即
“don’t mock types you don’t own”.

但是,如果您想要存根该代码,请尝试以下操作:

user = stub('fbgraph user', :friends => :foo_or_whatever_you_want)
FbGraph::User.stub_chain(:new,:fetch).and_return(user)

如果您需要检查消息期望,则需要更多的工作来从#new和#fetch返回模拟,并结合使用#should_receive.

点赞