检查班级是否在Rails进行测试前跳过操作

时间:2019-03-21 14:55:38

标签: ruby-on-rails

是否可以检查控制器是否针对某个特定动作具有skip_before_action

例如:

class AuthenticationController < ApplicationController
    skip_before_action :authenticate_user
    ...
end

然后检查类似这样的内容:

AuthenticationController.has_skip_before_action(:authenticate_user)?

我想对我的控制器测试进行此检查。如果RSpec有这样的东西,我可以使用。我正在使用Rails 5.1。

2 个答案:

答案 0 :(得分:3)

可以吗?否。类似于Veridian Dynamics所写的内容,您想要测试行为不一定是方法的存在。

也就是说,有可能这样做吗?是。这是一个适合您的玩具示例:

class AuthenticationController < ApplicationController
  skip_before_action :authenticate_user

  def index
  end
end

# authentication_controller_spec.rb
test "should get index" do
  # Have to make a request first to instantiate the controller variable
  get authentication_url

  # Convert this to a clearer method in your real code
  result = controller.__callbacks.first.last.map(&:filter).include?(:authenticate_user)

  # Assert on result ...
end

为解释代码,您使用AuthenticationController实例,并挖掘该实例的私有方法以获取回调列表。然后,您可以查找特定回调的存在与否。

这不是一个好的解决方案,我不禁在代码库中看到它们!此测试依赖于Rails框架的内部功能,该功能随时可能更改。这会使测试变得很脆弱,并且在框架升级期间可能会失败。任何检查此代码的同事都需要对为什么这是我们的代码库中的绝对必要性进行非常具体的解释。

答案 1 :(得分:2)

否,但是您可以通过验证:authenticate_user是不是还是没有进行预期工作来查看JobMap是否按预期工作。

与所有单元测试一样,这与“此方法是否存在吗?”无关,而与“此方法是否符合我们的期望?”无关。如果该方法不存在,我们将不检查它,因为我们不在乎。我们希望行为符合我们的期望,而不是代码。如果我们的代码不符合我们的期望,我们必须进行调查,阅读,重构等。但这是一项人工工作,而不是RSpec工作。

我假设您只是想变干,如果“ skip_before_authentication”已经存在,请避免检查身份验证,但这是一个非常糟糕的主意,即使有可能。