Search code examples
ruby-on-railsrubytestingrspecstubbing

Replace method implementation when stubbing with mocha


I'm used to RSpec in which you can stub a method implementation with a block which is evalueted lazily.

Now I'm working to a pull request for a project which uses Test::Unit and mocha as mocking library.

I need to be able to do something similar to the rspec example, i.e. replace a method implementation with a dynamic one which depends on object state, so I can not use static calls provided by mocha #returns method.

Is there any way to get the same functionality with mocha, I wasn't able to find any documentation on this?

I need to implement something similar to this (RSpec 2.14 syntax)

class SomeController < ApplicationController
  before_filter :authenticate

  def authenticate
    # original method I need to replace
  end

  def some_other_method
    :bar
  end

end

describe SomeController do

  before do
    controller.stub :authenticate do
      redirect_to root_path if some_other_method == :foo
    end
  end

  it 'should test something' do
    controller.stub(some_other_method: :foo)
    get :index
    response.should redirect_to root_path
  end

  it 'should test something else' do
    get :index
    response.should be_successful
  end

end

Solution

  • Can't you just use def on the controller instance?

    def controller.some_other_method
      :foo
    end