Nerian
Nerian

Reputation: 16177

RSpec: How do I stub a Sorcery method call in a controller?

Controller:

class SessionsController < ApplicationController
  layout 'login'

  def create
    user = login(params[:username], params[:password])
    if user
      redirect_back_or_to root_url
    else
      flash.now.alert = "Username or password was invalid"
      render :new
    end
  end
end

Test:

require 'spec_helper'

describe SessionsController do

  describe "POST create" do

    before(:each) { Fabricate(:school) }

    it "Should log me in" do      
      post(:create, {'password' => 'Secret', 'username' => 'director'})
      response.should redirect_to('/')
    end
  end

end

Fabricate(:school) has a callback that generates the first user. I want to refactor this code so that is doesn't use any database calls at all. I want to stub the login call so tht it returns true.

How could I stub the login method? It comes from Sorcery.

https://github.com/NoamB/sorcery/blob/master/lib/sorcery/controller.rb#L31

Upvotes: 4

Views: 584

Answers (1)

DangerDave
DangerDave

Reputation: 1955

Since the Sorcery login method is added as an instance method to the controller, you have to mock the method on the current controller instance, i.e. '@controller'. See http://api.rubyonrails.org/classes/ActionController/TestCase.html.

With Flexmock:

flexmock(@controller).should_receive(:login).and_return(flexmock('user')).once

Or RSpec mocks:

@controller.stub(:login) { double "user" }

Upvotes: 3

Related Questions