Rails:如何模拟宝石,例如fb_graph

时间:2012-04-17 20:48:51

标签: ruby-on-rails unit-testing rspec mocking 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)

谢谢!

1 个答案:

答案 0 :(得分:2)

我不会模仿gem中的代码,即"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