4

我正在使用 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)

谢谢!

4

1 回答 1

2

我不会从 gem 中模拟代码,即“不要模拟你不拥有的类型”

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

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

如果您需要检查消息期望,则需要更多的工作来从#newand#fetch中返回一个模拟,并结合 using #should_receive

于 2013-09-25T17:46:40.097 回答