【发布时间】:2019-07-28 11:12:20
【问题描述】:
我正在尝试为向 ActionController::Base 添加一些功能的 gem 编写测试。我想做这样的事情:
class TestController < ActionController::Base
def index
render json: { foo: "bar" }
end
end
RSpec.describe "foo" do
it "foo" do
controller = TestController.new
controller.process(:index)
end
end
但是,当我这样做时,undefined method 'has_content_type?' for nil:NilClass 会出错,因为请求 here 是 nil。
如何创建“假”请求对象,以便可以在控制器上设置它,如下所示:
controller = TestController.new
controller.request = ?
controller.process(:index)
【问题讨论】:
-
测试rails控制器直接实例化它们并调用方法是不常见的(因为,正如你所经历的,没有请求对象)。我建议使用 RSpec 指南来测试控制器 relishapp.com/rspec/rspec-rails/docs/controller-specs
-
@Bustkiller 我在 Rails 应用程序上下文之外复制 rspec 控制器测试时遇到了一些问题。你有如何做到这一点的例子吗?
-
对不起,我没有这样的例子。但是,您问题中的代码看起来很像 rails 应用程序。 “在 Rails 应用程序的上下文之外”是什么意思?
-
@Bustkiller 这些是对 gem 的测试,它为 actionpack 添加了一些功能,因此测试中没有应用程序上下文。
-
我最接近的方法是创建一个 Rails 引擎(一种特殊的 gem),它将一些模型、作业和控制器添加到应用程序中,包括它。在这类项目中,通常会有一个虚拟测试应用程序,包括运行测试的 gem。这提供了一个 Rails 测试环境,您可以像在常规 Rails 应用程序中一样无缝地使用 RSpec
标签: ruby-on-rails ruby rspec actioncontroller