如何在Rails的控制台中调用控制器/视图方法?

时间:2020-03-06 14:54:01  来源:igfitidea点击:

当我加载script / console时,有时候我想玩控制器或者视图助手方法的输出。

有什么方法可以:

  • 模拟一个请求?
  • 在请求中从控制器实例调用方法?
  • 测试帮助程序方法,是通过所述控制器实例还是其他方式?

解决方案

这是通过控制台执行此操作的一种方法:

>> 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将其方法混合到对象中,让我们查看其返回值。

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

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

./script/server -u

然后在脚本中插入一个断点,以便我们可以访问控制器/帮助器/等。

class EventsController < ApplicationController
  def index
    debugger
  end
end

并且,当我们发出请求并点击代码中的该部分时,服务器控制台将返回提示,然后我们可以在其中从命令提示符下发出请求,查看对象等。完成后,只需键入"继续"即可继续执行。也有用于扩展调试的选项,但这至少可以入门。

要调用助手,请使用helper对象:

$ ./script/console
>> helper.number_to_currency('123.45')
=> "R$ 123,45"

如果我们要使用默认情况下不包含的帮助程序(例如,因为我们已从ApplicationController中删除了helper:all),则只需包含该帮助程序即可。

>> include BogusHelper
>> helper.bogus
=> "bogus output"

至于与控制器打交道,我引用了尼克的回答:

> app.get '/posts/1'
> response = app.response
# you now have a rails response object much like the integration tests

> response.body            # get you the HTML
> response.cookies         # hash of the cookies

# etc, etc

较早的答案是调用助手,但以下答案将有助于调用控制器方法。我已经在2.2.3的导轨上使用了它。

首先将以下代码添加到.irbrc文件(可以位于主目录中)

class Object
   def request(options = {})
     url=app.url_for(options)
     app.get(url)
     puts app.html_document.root.to_s    
  end
end

然后在Rails控制台中,我们可以输入类似...

request(:controller => :show, :action => :show_frontpage)

...并且html将被转储到控制台。

从脚本/控制台调用控制器动作并查看/操纵响应对象的简单方法是:

> app.get '/posts/1'
> response = app.response
# you now have a rails response object much like the integration tests

> response.body            # get you the HTML
> response.cookies         # hash of the cookies

# etc, etc

该应用程序对象是ActionController :: Integration :: Session的实例

这对我使用Rails 2.1和2.3有用,我没有尝试使用早期版本。