[rspec-users] How to stub a class inside a module with Mocha in Ruby?

Toy Cc lists at ruby-forum.com
Tue Jan 29 13:15:49 UTC 2013

I know there are lot of questions in here around this. I've tried all of
them but none of them works. Basically, I'm trying to stub
TwitterOAuth::Client so my test won't call the real api every time.

Here's the bit from TwitterOAuth gem that I use.

module TwitterOAuth
  class Client

    def initialize(options = {})
      @consumer_key = options[:consumer_key]
      @consumer_secret = options[:consumer_secret]
      @token = options[:token]
      @secret = options[:secret]
      @proxy = options[:proxy]
      @debug = options[:debug]
      @api_version = options[:api_version] || '1'
      @api_host = options[:api_host] || 'api.twitter.com'
      @search_host = options[:search_host] || 'search.twitter.com'

    def request_token(options={})
      consumer(:secure => true).get_request_token(options)

The request_token is the method I'm trying to stub. And this is what
I've done in Sinatra which obviously doesn't work.

before '/' do
   @twitterClient = TwitterOAuth::Client.new(some_params_in_hash)

get '/login' do
   token = @twitterClient.request_token(callback)
   # do some other checking

And here's my test

it "should login with Twitter and save session" do

    #it's still going to the real twitter api.


I've read from somewhere that ruby mixin can be overridden in anywhere.
Clearly, I'm misunderstanding something.

The alternative way is I could wrap the gem again with class and then
stub from the class. Is that a good idea to do?

Please help.

Posted via http://www.ruby-forum.com/.

More information about the rspec-users mailing list