ruby-on-rails - 如何在 Controller 中测试实例变量?

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

我的几位导师告诉我要用 Controller 规范测试一段代码,即使内容正在通过某些请求规范进行测试。我想知道是否可以在 rspec Controller 测试中测试是否可以将像 @user 这样的实例变量设置为 someObjectnil

到目前为止,我已经尝试了几种不同的方法来对此进行测试,但我在 rspec 测试方面的技能至少可以说是初级的。我尝试的第一件事是模拟 current_user 和 'User.get_from_auth_user(current_user)。模拟对象打印良好并输出。问题是...我希望能够说出类似 expect(@user).to equal(mockedUser) 的内容,但这似乎永远行不通。我总是得到类似的东西:

Expect does not equal received
expected is nil
received is { someMockedObject }

这是我要测试的代码。

class ApplicationController < ActionController::Base
  before_action :set_user

  def set_user
    return if current_user.nil?

    @user = User.get_from_auth_user(current_user)
  end
end

我想知道我走的路是否正确,或者什么是全面测试这段代码的更好选择。我觉得答案应该很简单。

最佳答案

你的导师很愚蠢。虽然了解 Controller 规范可能很好,因为它们在遗留应用程序中无处不在,但将它们添加到新应用程序并不是一个好的做法。

For new Rails apps: we don't recommend adding the rails-controller-testing gem to your application. The official recommendation of the Rails team and the RSpec core team is to write request specs instead. Request specs allow you to focus on a single controller action, but unlike controller tests involve the router, the middleware stack, and both rack requests and responses. This adds realism to the test that you are writing, and helps avoid many of the issues that are common in controller specs.

DHH 很好地解释了测试 Controller 的实例变量有什么问题以及您应该做什么:

Testing what instance variables are set by your controller is a bad idea. That's grossly overstepping the boundaries of what the test should know about. You can test what cookies are set, what HTTP code is returned, how the view looks, or what mutations happened to the DB, but testing the innards of the controller is just not a good idea.

这就是为什么 assigns 被提取到一个单独的 gem。这一切都归结为测试您的代码做了什么 - 而不是它是如何做的。

参见:

关于ruby-on-rails - 如何在 Controller 中测试实例变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58403486/

相关文章:

ruby-on-rails - 如何使用 RVM 卸载 ruby​​ 和 gems?

ruby-on-rails - 如何在 Rails View 上显示错误消息?

c# - 如何在 NUnit 测试用例中传递字符串和字典?

javascript - 在 Sequelize 中模拟

ruby-on-rails - 为什么我的 Rails.root 为零?

ruby-on-rails - 如何防止 scaffold.css 覆盖我的自定义 css?

ruby-on-rails - 在 Prawn 中使用列表

ruby-on-rails - .rewind 方法对 ruby​​ 中的 Tempfile 做了什么?

ruby - 如何通过 Rack 提供二进制文件?

unit-testing - 如何打破 F# 中的函数依赖关系?