嘲笑from_omniauth方法进行测试? [重复]

问题描述 投票:0回答:1

这个问题在这里已有答案:

我想测试else分支。我在下面写了“TEST THIS BRANCH”。要在@ user.persisted中找到该分支?应该是假的。 from_omniauth在用户模型中定义。

class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController


  def facebook
    # You need to implement the method below in your model (e.g. app/models/user.rb)
    @user = User.from_omniauth(request.env["omniauth.auth"])

    if @user.persisted? 

      flash[:notice] = I18n.t 'devise.omniauth_callbacks.success', kind: 'Facebook'
      sign_in_and_redirect @user, event: :authentication

    else
      //TEST THIS BRANCH
      session["devise.facebook_data"] = request.env["omniauth.auth"]
      redirect_to new_user_session_url, alert: @user.errors.full_messages.join("\n")
    end
  end


end

用户模型定义如下:

class User < ApplicationRecord

  def self.from_omniauth(auth)

    where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
      user.email = auth.info.email ? auth.info.email : Devise.friendly_token[0,20] + "@" + Devise.friendly_token[0,20] + ".com"
      user.password = Devise.friendly_token[0,20]
    end

  end
end

我正在使用rspec和capybara进行功能测试。我怎么能模拟self.from_omniauth(auth)以便我可以测试else分支?我很欣赏任何有关如何正确执行此操作的见解。谢谢!

ruby-on-rails capybara omniauth rspec-rails
1个回答
0
投票

在进行功能测试时,您不应该嘲笑任何自己的代码,因为它会破坏端到端功能测试的全部要点。您可以做的是启用omniauth测试模式 - https://github.com/omniauth/omniauth/wiki/Integration-Testing - 并使用它来提供您想要的任何OAuth响应,从而使您的代码返回满足分支需要的任何内容。在您目前的情况下,我猜这将是一个与现有用户具有相同电子邮件地址的响应,但是不同的提供者/ uid(假设您的电子邮件列必须是唯一的)

© www.soinside.com 2019 - 2024. All rights reserved.