gpt4 book ai didi

ruby - 使用 Minitest 对 protected 或私有(private)方法进行 stub

转载 作者:行者123 更新时间:2023-11-28 20:31:13 24 4
gpt4 key购买 nike

如何在功能 Controller 测试中 stub 要通过的私有(private)/ protected 方法?

以如下代码为例:

app/controllers/sessions_controller.rb

class SessionsController < ApplicationController
def create
@user = User.from_omniauth(auth_hash)
reset_session
session[:user_nickname] = @user.nickname

if @user.email.blank?
redirect_to edit_user_path(@user.nickname), :alert => "Please enter your email address."
else
redirect_to show_user_path(@user.nickname), :notice => 'Signed in!'
end
end

private

def auth_hash
request.env['omniauth.auth']
end
end

我尝试了以下方法:

test/controllers/sessions_controller_unit_test.rb

require 'test_helper'
class SessionsControllerTest < ActionController::TestCase

test "should create new user" do

# get the same 'request.env['omniauth.auth'] hash
auth_h = OmniAuth.config.mock_auth[:github]

# but auth_hash is never passed in User.find_or_create_from_auth_hash(auth_hash)
# method, which result to be nil breaking the User model call
get :create, provider: 'github', nickname: 'willishake', auth_hash: auth_h

assert_redirected_to show_user_path(nickname: 'willishake')
assert_equal session[:user_id], "willishake"
end
end

但是当 get :create (测试方法)调用时模型 User.find_or_create_from_auth_hash(auth_hash),auth_hash 为 nil,破坏了功能测试。

那么什么是 stub auth_hash 私有(private)方法并传递给用户模型调用 User.from_omniauth(auth_hash) 的正确方法?

更新:在 blowmage 建议之后,它的工作原理如下:

require 'test_helper'
class SessionsControllerTest < ActionController::TestCase

def setup
request.env['omniauth.auth'] = OmniAuth.config.mock_auth[:github]
end

test "should create new user" do
get :create, provider: 'github', nickname: 'willishake'

assert_equal session[:user_id], "willishake"
assert_redirected_to show_user_path(nickname: 'willishake')
end
end

最佳答案

试试这个:

# set the request.env['omniauth.auth'] hash
auth_h = OmniAuth.config.mock_auth[:github]
request.env['omniauth.auth'] = auth_h

关于ruby - 使用 Minitest 对 protected 或私有(private)方法进行 stub ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24232027/

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