【问题标题】:How to test a Rails Class function in the console?如何在控制台中测试 Rails 类功能?
【发布时间】:2016-03-20 07:05:09
【问题描述】:

我正在尝试在 rails 控制台的 Rails 类中测试一些功能。

class Model
  def function1
    input_1 = ...
    input_2 = ...
    function1_hash = [ ]
    ...
    m = function2(input_1,input_2)
    function1_hash += m
  end

  def function2(input_1,input_2)
    input_1.each do |value|
      function2_hash << value
    end

    temp = input_2.anotherClassFunctionCall()
    function2_hash << temp
  end
end

所以在 Rails 控制台中,我试图查看这些功能是否正常工作,但我一直遇到以下错误。

# Rails console
> input_1 = ...
> input_2 = ...
> Model.function2(input_1,input_2)
NoMethodError: undefined method `function2' for Model:Class

最终,我需要对 function1 进行健全性检查(这在更大的工作流程中肯定会失败),但似乎甚至无法识别它在同一类中所依赖的函数。

顺便说一句,整个 rails 都作为 Docker 文件上传到 AWS ELB 实例中。我正在使用 eb ssh 来访问 rails 并执行上述测试。

【问题讨论】:

    标签: ruby-on-rails ruby amazon-web-services console amazon-elastic-beanstalk


    【解决方案1】:

    您的function2 是一个实例方法。您需要在 Model 类的实例上调用它,例如:

    Model.new.function2(input_1,input_2)
    

    编码愉快!

    【讨论】:

    • 感谢您的意见。在 function1 之前有一个单独的 def init 函数,当我使用您的: Model.new.function2(input_1,input_2) 我得到嵌入的相同异常错误def function1 当我运行一般 Model.create!(input_variable: some_varialbe) (--> 这是我需要工作):rescue Exception => e run_errors
    【解决方案2】:

    你可以让你的方法成为类方法

    变化:

    def function2(input_1,input_2)
    

    到:

    def self.function2(input_1,input_2)
    

    【讨论】:

      猜你喜欢
      • 2016-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-30
      • 2019-03-06
      • 2023-03-27
      相关资源
      最近更新 更多