gpt4 book ai didi

ruby-on-rails-3 - 在请求规范中 stub 身份验证

转载 作者:行者123 更新时间:2023-12-03 05:09:35 25 4
gpt4 key购买 nike

编写请求规范时,如何设置 session 和/或 stub Controller 方法?我正在尝试在集成测试中消除身份验证 - rspec/requests

这是一个测试示例

require File.dirname(__FILE__) + '/../spec_helper'
require File.dirname(__FILE__) + '/authentication_helpers'


describe "Messages" do
include AuthenticationHelpers

describe "GET admin/messages" do
before(:each) do
@current_user = Factory :super_admin
login(@current_user)
end

it "displays received messages" do
sender = Factory :jonas
direct_message = Message.new(:sender_id => sender.id, :subject => "Message system.", :content => "content", :receiver_ids => [@current_user.id])
direct_message.save
get admin_messages_path
response.body.should include(direct_message.subject)
end
end
end

助手:

module AuthenticationHelpers
def login(user)
session[:user_id] = user.id # session is nil
#controller.stub!(:current_user).and_return(user) # controller is nil
end
end

以及处理身份验证的ApplicationController:

class ApplicationController < ActionController::Base
protect_from_forgery

helper_method :current_user
helper_method :logged_in?

protected

def current_user
@current_user ||= User.find(session[:user_id]) if session[:user_id]
end

def logged_in?
!current_user.nil?
end
end

为什么无法访问这些资源?

1) Messages GET admin/messages displays received messages
Failure/Error: login(@current_user)
NoMethodError:
undefined method `session' for nil:NilClass
# ./spec/requests/authentication_helpers.rb:3:in `login'
# ./spec/requests/message_spec.rb:15:in `block (3 levels) in <top (required)>'

最佳答案

请求规范是 ActionDispatch::IntegrationTest 的薄包装。 ,它不像 Controller 规范(包装 ActionController::TestCase )那样工作。尽管有可用的 session 方法,但我认为它不受支持(即它可能存在,因为其他实用程序包含的模块也包含该方法)。

我建议通过发布到您用来验证用户身份的任何操作来登录。如果您为所有用户工厂设置密码“password”(例如),那么您可以执行以下操作:

def login(user)  post login_path, :login => user.login, :password => 'password'end

关于ruby-on-rails-3 - 在请求规范中 stub 身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5787409/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com