【问题标题】:mocking from_omniauth method for testing? [duplicate]模拟 from_omniauth 方法进行测试? [复制]
【发布时间】:2018-09-04 02:32:37
【问题描述】:

我想测试 else 分支。我在下面写了“测试这个分支”。要打那个分支@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

User模型定义如下:

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 分支?我很欣赏有关如何正确执行此操作的任何见解。谢谢!

【问题讨论】:

  • 看看this是否有帮助。

标签: ruby-on-rails capybara omniauth rspec-rails


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2018-12-23
    • 2022-06-15
    • 2023-03-09
    • 2023-02-01
    • 2016-07-20
    • 2023-03-18
    • 2017-02-03
    • 2013-08-05
    • 2011-12-09
    相关资源
    最近更新 更多