使用Minitest对受保护或私有方法进行存根

时间:2014-06-15 17:06:29

标签: ruby testing tdd integration-testing minitest

如何在功能控制器测试中传递私有/受保护的方法?

以下代码为例:

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

我尝试了以下内容:

测试/控制器/ 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为零,打破了功能测试。

那么,什么是存储auth_hash私有方法并传递给用户模型调用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

1 个答案:

答案 0 :(得分:2)

试试这个:

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