【问题标题】:Mock out a hash in Rails/Rspec在 Rails/Rspec 中模拟一个哈希
【发布时间】:2016-08-29 18:49:55
【问题描述】:

我需要模拟一个自动提供给我的控制器的哈希。我目前正在尝试为我的应用程序控制器编写 Rspec 测试。它需要从内部 gem 获取用户信息(所以我无法使用我在模拟会话哈希中看到的任何解决方案)并用它们填充我们的用户字段。

  # Create and store the user if they have never logged in before, set user if they have an existing record
  def logged_in_user
    @logged_in_user ||= User.find_by(id: current_user['id']) || create_user
  end

  def create_user
    User.create(name: current_user['name'], email: current_user['email'], id: current_user['id'])
  end

current_user 是由我们的内部登录 gem 提供的哈希值,我添加到代码中以获取它的唯一内容是 routes.rb 中的“mount ....”(未检索到/ 要求我的控制器中的任何其他内容,这是唯一使用它的地方)。我知道我的代码有效,因为我可以登录到页面并看到我的用户信息已保存,但我需要编写涵盖所有方法的 Rspec 测试。我尝试定义一个名为“current_user”的哈希,但仍然收到错误消息,告诉我“[]”是类上的未定义方法:NilClass。我曾尝试使用 allow(method).to receive(current_user) 但是当我这样做时,我们的代码覆盖工具告诉我从未到达 create user 语句的内部

【问题讨论】:

    标签: ruby-on-rails ruby unit-testing rspec


    【解决方案1】:

    试试这个代码

    allow_any_instance_of(ApplicationController).
      to receive(:current_user).
      and_return({
        "name" => "your stubbed name",
        "email" => "stubbed email",
        "id" => "100"
      })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-31
      • 2018-04-09
      • 2016-11-27
      • 1970-01-01
      • 2016-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多