What is the best way to mock a 3rd party object in ruby?

Posted by spinlock on Stack Overflow See other posts from Stack Overflow or by spinlock
Published on 2011-11-29T17:48:06Z Indexed on 2011/11/29 17:49 UTC
Read the original article Hit count: 223

Filed under:
|
|
|

I'm writing a test app using the twitter gem and I'd like to write an integration test but I can't figure out how to mock the objects in the Twitter namespace. Here's the function that I want to test:

def build_twitter(omniauth)
  Twitter.configure do |config|
    config.consumer_key = TWITTER_KEY
    config.consumer_secret = TWITTER_SECRET
    config.oauth_token = omniauth['credentials']['token']
    config.oauth_token_secret = omniauth['credentials']['secret']
  end
  client = Twitter::Client.new
  user = client.current_user
  self.name = user.name
end

and here's the rspec test that I'm trying to write:

feature 'testing oauth' do
  before(:each) do
    @twitter = double("Twitter")
    @twitter.stub!(:configure).and_return true
    @client = double("Twitter::Client")
    @client.stub!(:current_user).and_return(@user)
    @user = double("Twitter::User")
    @user.stub!(:name).and_return("Tester")
  end

  scenario 'twitter' do

    visit root_path
    login_with_oauth

    page.should have_content("Pages#home")
  end
end

But, I'm getting this error:

1) testing oauth twitter
   Failure/Error: login_with_oauth
   Twitter::Error::Unauthorized:
     GET https://api.twitter.com/1/account/verify_credentials.json: 401: Invalid / expired Token
   # ./app/models/user.rb:40:in `build_twitter'
   # ./app/models/user.rb:16:in `build_authentication'
   # ./app/controllers/authentications_controller.rb:47:in `create'
   # ./spec/support/integration_spec_helper.rb:3:in `login_with_oauth'
   # ./spec/integration/twit_test.rb:16:in `block (2 levels) in <top (required)>'

The mocks above are using rspec but I'm open to trying mocha too. Any help would be greatly appreciated.

© Stack Overflow or respective owner

Related posts about ruby

Related posts about testing