猿问
下载APP

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

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

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

有办法:

  • 模拟请求?

  • 在所述请求上从控制器实例调用方法?

  • 通过所述控制器实例或其他方式测试助手方法?


慕婉清6462132
浏览 52回答 3
3回答

Qyouu

要调用帮助程序,请使用以下helper对象:$ ./script/console>> helper.number_to_currency('123.45')=> "R$ 123,45"如果您想使用默认情况下未包含的帮助程序(例如,因为您已helper :all从中删除ApplicationController),只需包含帮助程序即可。>> 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

慕雪6442864

从脚本/控制台调用控制器操作并查看/操作响应对象的简单方法是:> 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, etcapp对象是ActionController :: Integration :: Session的一个实例这适用于我使用Rails 2.1和2.3,我没有尝试早期版本。

PIPIONE

如果您需要从控制台进行测试(在Rails 3.1和4.1上测试):呼叫控制器动作:app.get '/'&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp;app.response&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp;app.response.headers&nbsp; # => { "Content-Type"=>"text/html", ... }&nbsp; &nbsp;app.response.body&nbsp; &nbsp; &nbsp;# => "<!DOCTYPE html>\n<html>\n\n<head>\n..."&nbsp;ApplicationController方法:foo = ActionController::Base::ApplicationController.newfoo.public_methods(true||false).sortfoo.some_method&nbsp;路线助手:app.myresource_path&nbsp; &nbsp; &nbsp;# => "/myresource"&nbsp;app.myresource_url&nbsp; &nbsp; &nbsp; # => "http://www.example.com/myresource"查看助手:foo = ActionView::Base.newfoo.javascript_include_tag 'myscript' #=> "<script src=\"/javascripts/myscript.js\"></script>"helper.link_to "foo", "bar" #=> "<a href=\"bar\">foo</a>"ActionController::Base.helpers.image_tag('logo.png')&nbsp; #=> "<img alt=\"Logo\" src=\"/images/logo.png\" />"渲染:views = Rails::Application::Configuration.new(Rails.root).paths["app/views"]views_helper = ActionView::Base.new viewsviews_helper.render 'myview/mytemplate'views_helper.render file: 'myview/_mypartial', locals: {my_var: "display:block;"}views_helper.assets_prefix&nbsp; #=> '/assets'ActiveSupport方法:require 'active_support/all'1.week.ago=> 2013-08-31 10:07:26 -0300a = {'a'=>123}a.symbolize_keys=> {:a=>123}Lib模块:> require 'my_utils'&nbsp;=> true&nbsp;> include MyUtils&nbsp;=> Object&nbsp;> MyUtils.say "hi"evaluate: hi&nbsp;=> true&nbsp;
打开App,查看更多内容
随时随地看视频慕课网APP
我要回答