【问题标题】:How would I mock `request.xhr?` in a Rails 5 helper spec?我将如何在 Rails 5 辅助规范中模拟“request.xhr?”?
【发布时间】:2020-10-20 17:42:37
【问题描述】:

我正在 rspec 中测试 Rails 5 助手。我们在一个帮助器中有一个块,它被包裹在一个条件中:

if request.xhr?
  # do stuff
end

在规范中,我无法强制 request.xhr? 测试返回 true。我试过allow_any_instance_of(ActionController::Request).to receive(:xhr?).and_return(true),但上面写着Undefined Constant ActionController::Request(有点道理)。我也试过allow(request).to receive(:xhr?).and_return(true),但只是默默地失败了。

我该如何测试 - #do stuff 代码是否在我们希望的时候执行,以及它是否符合我们的预期?

【问题讨论】:

    标签: ruby-on-rails-5 rspec-rails


    【解决方案1】:

    答案竟然是allow_any_instance_of(ActionDispatch::Request).to receive(:xhr?).and_return(true)。我错过了 Request 对象已移出 ActionController 模块并进入 ActionDispatch。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-24
      • 1970-01-01
      • 1970-01-01
      • 2021-05-20
      相关资源
      最近更新 更多