【发布时间】:2014-06-15 17:06:28
【问题描述】:
如何存根私有/受保护的方法以在功能控制器测试中传递?
以如下代码为例:
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,功能测试失败。
那么,存根 auth_hash 私有方法并传递给用户模型调用 User.from_omniauth(auth_hash) 的正确方法是什么?
更新: 根据吹法师的建议,它的工作原理如下:
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
【问题讨论】:
标签: ruby testing tdd integration-testing minitest