如何在rails功能测试中获取当前控制器对象的句柄/引用?

时间:2021-06-22 16:57:23

I must be missing something very simple, but can't find the answer to this. I have a method named foo inside bar_controller. I simply want to call that method from inside a functional test.

我必须遗漏一些非常简单的东西,但找不到答案。我在bar_controller中有一个名为foo的方法。我只是想从功能测试中调用该方法。

Here's my controller:

这是我的控制器:

class BarsController < ApplicationController
  def foo
    # does stuff
  end
end

Here's my functional test:

这是我的功能测试:

class BarsControllerTest << ActionController::TestCase
  def "test foo" do
    # run foo
    foo
    # assert stuff
  end
end

When I run the test I get:

当我运行测试时,我得到:

NameError: undefined local variable or method `foo' for #<BarsControllerTest:0x102f2eab0>

All the documentation on functional tests describe how to simulate a http get request to the bar_controller which then runs the method. But I'd just like to run the method without hitting it with an http get or post request. Is that possible?

所有关于功能测试的文档都描述了如何模拟对bar_controller的http get请求,然后bar_controller运行该方法。但我只是想运行该方法而不用http get或post请求命中它。那可能吗?

There must be a reference to the controller object inside the functional test, but I'm still learning ruby and rails so need some help.

在功能测试中必须有对控制器对象的引用,但我还在学习ruby和rails,所以需要一些帮助。

2 个解决方案

#1


3  

I found the answer in "Agile Web Development with Rails" Book. ActionController::TestCase initializes three instance variables needed by every functional test: @controller (contains instance of controller under test), @request, and @response.

我在“使用Rails进行敏捷Web开发”一书中找到了答案。 ActionController :: TestCase初始化每个功能测试所需的三个实例变量:@controller(包含被测控制器的实例),@ request和@response。

#2


0  

You need call this action with HTTP verb like

你需要用HTTP动词来调用这个动作

get :foo
post :foo

etc...

#1


3  

I found the answer in "Agile Web Development with Rails" Book. ActionController::TestCase initializes three instance variables needed by every functional test: @controller (contains instance of controller under test), @request, and @response.

我在“使用Rails进行敏捷Web开发”一书中找到了答案。 ActionController :: TestCase初始化每个功能测试所需的三个实例变量:@controller(包含被测控制器的实例),@ request和@response。

#2


0  

You need call this action with HTTP verb like

你需要用HTTP动词来调用这个动作

get :foo
post :foo

etc...