巫术认证宝典:https://github.com/NoamB/sorcery
Sorcery的创建者提供了一个示例Rails应用程序,其Test::Unit功能测试中包含Sorcery测试助手:https://github.com/NoamB/sorcery-example-app/blob/master/test/functional/users_controller_test.rb
# Test::Unit functional test example
require 'test_helper'
class UsersControllerTest < ActionController::TestCase
setup do
@user = users(:noam)
end
test "should show user" do
login_user
get :show, :id => @user.to_param
assert_response :success
end
但是我不知道如何在我的RSpec Controller 规范中使
login_user
工作。/gems/sorcery-0.7.5/lib/sorcery/test_helpers/rails.rb:7:in `login_user':
undefined method `auto_login' for nil:NilClass (NoMethodError)
这是在Sorcery gem中有关上述错误的相关代码:
https://github.com/NoamB/sorcery/blob/master/lib/sorcery/test_helpers/rails.rb
module Sorcery
module TestHelpers
module Rails
# logins a user and calls all callbacks
def login_user(user = nil)
user ||= @user
@controller.send(:auto_login,user)
@controller.send(:after_login!,user,[user.send(user.sorcery_config.username_attribute_names.first),'secret'])
end
def logout_user
@controller.send(:logout)
end
end
end
end
更新:
根据巫术的文档“Testing in Rails 3”,我确实已将
include Sorcery::TestHelpers::Rails
添加到我的spec_helper.rb
中。巫术测试帮助程序
login_user
对@controller
起作用,但由于在 Controller 规范中@controller
是nil
,因此出现了错误。这是我的规范:#spec/controllers/forums_controller_spec.rb
require 'spec_helper'
describe ForumsController do
render_views
describe 'GET new' do
describe 'when guest' do
it 'should deny and redirect' do
get :new
response.should redirect_to(root_path)
end
end
describe 'when admin' do
p @controller #=> nil
@user = User.create!(username: "Test", password: "secret", email: "[email protected]")
login_user # <--------------- where the error occurs
it 'should resolve' do
get :new
response.should render_template(:new)
end
end
end
end
最佳答案
FWIW,我花了很多时间寻找这个问题的答案。我正在使用Capybara和RSpec。事实证明,您需要手动登录才能使用Sorcery才能使登录生效。
我已经在此处通过Sorcery/Rspec/Capybara创建集成测试创建了一个要点:
https://gist.github.com/2359120/9989c14af19a48ba726240d030c414b882b96a8a
关于ruby - 如何在我的RSpec测试中访问法术?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8708320/