当我加载脚本/控制台时,有时我想使用控制器或视图助手方法的输出。

有没有办法:

模拟一个请求? 从控制器实例调用方法说请求? 测试助手方法,无论是通过所说的控制器实例或其他方式?


当前回答

如果方法是POST方法,那么:

app.post 'controller/action?parameter1=value1&parameter2=value2'

(这里的参数将根据您的适用性而定。)

如果是GET方法,则:

app.get 'controller/action'

其他回答

对于控制器,可以在Ruby on Rails控制台中实例化控制器对象。

例如,

class CustomPagesController < ApplicationController

  def index
    @customs = CustomPage.all
  end

  def get_number
    puts "Got the Number"
  end

  protected

  def get_private_number
    puts 'Got private Number'
  end

end

custom = CustomPagesController.new
2.1.5 :011 > custom = CustomPagesController.new
 => #<CustomPagesController:0xb594f77c @_action_has_layout=true, @_routes=nil, @_headers={"Content-Type"=>"text/html"}, @_status=200, @_request=nil, @_response=nil>
2.1.5 :014 > custom.get_number
Got the Number
 => nil

# For calling private or protected methods,
2.1.5 :048 > custom.send(:get_private_number)
Got private Number
 => nil

你可以像下面这样在Ruby on Rails控制台中访问你的方法:

controller.method_name
helper.method_name

这里有一种方法可以通过控制台做到这一点:

>> foo = ActionView::Base.new
=> #<ActionView::Base:0x2aaab0ac2af8 @assigns_added=nil, @assigns={}, @helpers=#<ActionView::Base::ProxyModule:0x2aaab0ac2a58>, @controller=nil, @view_paths=[]>

>> foo.extend YourHelperModule
=> #<ActionView::Base:0x2aaab0ac2af8 @assigns_added=nil, @assigns={}, @helpers=#<ActionView::Base::ProxyModule:0x2aaab0ac2a58>, @controller=nil, @view_paths=[]>

>> foo.your_helper_method(args)
=> "<html>created by your helper</html>"

创建ActionView::Base的新实例可以让你访问你的助手可能使用的普通视图方法。然后扩展YourHelperModule,将它的方法混合到你的对象中,让你查看它们的返回值。

另一种方法是使用Ruby on Rails调试器。http://guides.rubyonrails.org/debugging_rails_applications.html上有一个关于调试的Ruby on Rails指南

基本上,使用-u选项启动服务器:

./script/server -u

然后在脚本中插入一个断点,在这个断点中您可以访问控制器、助手等。

class EventsController < ApplicationController
  def index
    debugger
  end
end

当您发出请求并点击代码中的该部分时,服务器控制台将返回一个提示符,然后您可以从命令提示符发出请求、查看对象等。完成后,只需输入'cont'继续执行。也有扩展调试的选项,但这至少可以让您开始。

在Ruby on Rails控制台中测试Helper方法的一种可能方法是:

Struct.new(:t).extend(YourHelper).your_method(*arg)

和重载做:

reload!; Struct.new(:t).extend(YourHelper).your_method(*arg)