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

强颜欢笑 提交于 2020-02-26 07:31:42

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

有办法:

  • 模拟请求?
  • 在所述请求上从控制器实例调用方法?
  • 通过所述控制器实例或其他方式测试助手方法?

#1楼

要调用帮助程序,请使用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楼

之前的答案是调用帮助程序,但以下内容将有助于调用控制器方法。 我在Ruby on Rails 2.3.2上使用过它。

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

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

然后在Ruby on Rails控制台上,您可以输入类似......

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

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


#3楼

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

> app.get '/posts/1'
> response = app.response
# You now have a Ruby on Rails response object much like the integration tests

> response.body            # Get you the HTML
> response.cookies         # Hash of the cookies

# etc., etc.

app对象是ActionController :: Integration :: Session的一个实例

这适用于我使用Ruby on Rails 2.1和2.3,我没有尝试早期版本。


#4楼

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

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


#5楼

在Ruby on Rails 3中,试试这个:

session = ActionDispatch::Integration::Session.new(Rails.application)
session.get(url)
body = session.response.body

正文将包含URL的HTML。

如何在Ruby on Rails 3中从模型路由和呈现(调度)

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!