RSpec:如何在控制器中存根Sorcery方法调用?

时间:2011-11-10 20:25:56

标签: refactoring rspec

控制器:

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

测试:

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)有一个生成第一个用户的回调。我想重构此代码,以便根本不使用任何数据库调用。我想存根登录调用,所以它返回true。

我怎样才能存根login方法?它来自巫术。

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

1 个答案:

答案 0 :(得分:3)

由于Sorcery登录方法作为实例方法添加到控制器,您必须在当前控制器实例上模拟该方法,即“@controller”。请参阅http://api.rubyonrails.org/classes/ActionController/TestCase.html

使用Flexmock:

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

或RSpec模拟:

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