ruby – 从TestCase调用Sinatra app实例方法

前端之家收集整理的这篇文章主要介绍了ruby – 从TestCase调用Sinatra app实例方法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个util方法进入Sinatra应用程序,我想从我的TestCase测试.

问题是,我不知道如何调用它,如果我只是使用app.util_method我有错误NameError:undefined局部变量或方法’util_method’为#< Sinatra :: ExtendedRack:0x007fc0c43305b8>

my_app.rb:

class MyApp < Sinatra::Base
  # [...] routes methods

  # utils methods
  def util_method
    return "hi"
  end
end

my_app_test.rb:

require "my_app.rb"
require "test/unit"
require "rack/test"

class MyAppTest < Test::Unit::TestCase
  include Rack::Test::Methods

  def app
    MyApp.new
  end

  # [...] routes methods tests

  def test_util_method
    assert_equal( "hi",app.util_method )
  end
end

解决方法

Sinatra aliases the new method to new!在重新定义之前,所以最简单的解决方案是使用它:
def app
  MyApp.new!
end

当然,我只注意到,在我想出以下内容之后,我会留下来,因为它可能是有用的/翔实的.

一个可能的方法来让Sinatra redefining the new method and returning a complete Rack app得到一个实例,你的实际基础是做自己的“真正的”新方法

def app
  a = MyApp.allocate
  a.send :initialize
  a
end

这是一个黑客,但它可能是有用的测试.

另一种技术将是“走”中间件堆栈,直到你上课.以下是有点脆弱的,因为它取决于使用名称@app来引用堆栈中的下一个应用程序的所有中间件,但这是相当普遍的.

def app
  a = MyApp.new
  while a.class != MyApp
    a = a.instance_variable_get(:@app)
  end
  a
end

这不会在尚未发布的Sinatra 1.4(至少不在当前的主人,即commit 41840746e866e8e8e9a0eaafc53d8b9fe6615b12),因为新的现在返回Wrapper class,循环永远不会结束.在这种情况下,您可以直接从@instance变量获取基类:

def app
  MyApp.new.instance_variable_get :@instance
end

(注意,最后的技术可能会在最终1.4版本之前更改).

原文链接:https://www.f2er.com/ruby/272836.html

猜你在找的Ruby相关文章