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

发布于 2024-12-15 06:35:23 字数 993 浏览 0 评论 0原文

控制器:

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

岁月无声 2024-12-22 06:35:23

由于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" }

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" }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文