RSpec:如何在控制器中存根 Sorcery 方法调用?
控制器:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于Sorcery登录方法作为实例方法添加到控制器中,因此您必须在当前控制器实例上模拟该方法,即“@controller”。请参阅http://api.rubyonrails.org/classes/ActionController/TestCase.html。
使用 Flexmock:
或 RSpec 模拟:
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:
Or RSpec mocks: