Karan
Karan

Reputation: 15104

Rails: How to mock gems, such as fb_graph

I am using the gem fb_graph. I am new to rails, and am trying to figure out how to mock this gem using rspec. ( https://github.com/nov/fb_graph )

The code I am attempting to test is:

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

I was thinking something along the following lines:

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)

Thanks!

Upvotes: 4

Views: 944

Answers (1)

Kenrick Chien
Kenrick Chien

Reputation: 1046

I wouldn't mock code from a gem, i.e. "don't mock types you don't own".

However, if you wanted to stub that code, try this:

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

If you need to check message expectations, it will require a bit more work to return a mock from #new and #fetch, in combination with using #should_receive.

Upvotes: 2

Related Questions