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

kch*_*kch 428 console ruby-on-rails

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

有办法:

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

kch*_*kch 472

要调用帮助程序,请使用以下helper对象:

$ ./script/console
>> helper.number_to_currency('123.45')
=> "R$ 123,45"
Run Code Online (Sandbox Code Playgroud)

如果您想使用默认情况下未包含的帮助程序(例如,因为您已helper :all从中删除ApplicationController),只需包含帮助程序即可.

>> include BogusHelper
>> helper.bogus
=> "bogus output"
Run Code Online (Sandbox Code Playgroud)

至于处理控制器,我引用尼克的回答:

> 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
Run Code Online (Sandbox Code Playgroud)

  • 我观察到我不能执行多个`app.get`(线程错误随之而来).有没有办法可以刷新系统并执行更多的获取? (4认同)
  • 注意在Rails 3.2中这不起作用.我需要从控制台调用`url_for`.为此,我做了'app.url_for(...)` (2认同)
  • @RudolfOlah似乎如果您使用设备(或典狱长),您可以使用 `ActionDispatch::Integration::Session.include(Warden::Test::Helpers); 来完成此操作。Warden.test_mode!; app.login_as(User.find(1), 范围: :user)`。 (2认同)

Nic*_*ick 145

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

> 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.
Run Code Online (Sandbox Code Playgroud)

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

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

  • 您应该可以发布到登录页面,例如:app.post'/ session/new',{:username =>"foo",:password =>"pass"}.然后继续使用相同的"app"变量来获取页面. (7认同)
  • 如何验证控制台,以便检查需要验证的控制器? (4认同)
  • 关于app对象的官方文档的链接会很好. (2认同)

Fer*_*eti 104

如果您需要从控制台进行测试(在Rails 3.1和4.1上测试):

呼叫控制器动作:

app.get '/'
   app.response
   app.response.headers  # => { "Content-Type"=>"text/html", ... }
   app.response.body     # => "<!DOCTYPE html>\n<html>\n\n<head>\n..."
Run Code Online (Sandbox Code Playgroud)

ApplicationController方法:

foo = ActionController::Base::ApplicationController.new
foo.public_methods(true||false).sort
foo.some_method
Run Code Online (Sandbox Code Playgroud)

路线助手:

app.myresource_path     # => "/myresource"
app.myresource_url      # => "http://www.example.com/myresource"
Run Code Online (Sandbox Code Playgroud)

查看助手:

foo = ActionView::Base.new

foo.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')  #=> "<img alt=\"Logo\" src=\"/images/logo.png\" />"
Run Code Online (Sandbox Code Playgroud)

渲染:

views = Rails::Application::Configuration.new(Rails.root).paths["app/views"]
views_helper = ActionView::Base.new views
views_helper.render 'myview/mytemplate'
views_helper.render file: 'myview/_mypartial', locals: {my_var: "display:block;"}
views_helper.assets_prefix  #=> '/assets'
Run Code Online (Sandbox Code Playgroud)

ActiveSupport方法:

require 'active_support/all'
1.week.ago
=> 2013-08-31 10:07:26 -0300
a = {'a'=>123}
a.symbolize_keys
=> {:a=>123}
Run Code Online (Sandbox Code Playgroud)

Lib模块:

> require 'my_utils'
 => true
> include MyUtils
 => Object
> MyUtils.say "hi"
evaluate: hi
 => true
Run Code Online (Sandbox Code Playgroud)


Gor*_*son 74

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

>> 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>"
Run Code Online (Sandbox Code Playgroud)

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


Dan*_*vin 14

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

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

./script/server -u
Run Code Online (Sandbox Code Playgroud)

然后在您希望有权访问控制器/帮助程序/等的脚本中插入断点.

class EventsController < ApplicationController
  def index
    debugger
  end
end
Run Code Online (Sandbox Code Playgroud)

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

  • > =>注意:自Ruby 2.0以来,调试器选项被忽略,将来的版本将删除它. (2认同)

Swa*_*kar 14

如果方法是POST方法那么

app.post 'controller/action?parameter1=value1&parameter2=value2'
Run Code Online (Sandbox Code Playgroud)

[此处参数将根据您的适用性]

否则如果是GET方法那么

app.get 'controller/action'
Run Code Online (Sandbox Code Playgroud)


Chl*_*loe 12

以下是使用Refinery作为示例进行经过身份验证的POST请求的方法:

# Start Rails console
rails console
# Get the login form
app.get '/community_members/sign_in'
# View the session
app.session.to_hash
# Copy the CSRF token "_csrf_token" and place it in the login request.
# Log in from the console to create a session
app.post '/community_members/login', {"authenticity_token"=>"gT7G17RNFaWUDLC6PJGapwHk/OEyYfI1V8yrlg0lHpM=",  "refinery_user[login]"=>'chloe', 'refinery_user[password]'=>'test'}
# View the session to verify CSRF token is the same
app.session.to_hash
# Copy the CSRF token "_csrf_token" and place it in the request. It's best to edit this in Notepad++
app.post '/refinery/blog/posts', {"authenticity_token"=>"gT7G17RNFaWUDLC6PJGapwHk/OEyYfI1V8yrlg0lHpM=", "switch_locale"=>"en", "post"=>{"title"=>"Test", "homepage"=>"0", "featured"=>"0", "magazine"=>"0", "refinery_category_ids"=>["1282"], "body"=>"Tests do a body good.", "custom_teaser"=>"", "draft"=>"0", "tag_list"=>"", "published_at(1i)"=>"2014", "published_at(2i)"=>"5", "published_at(3i)"=>"27", "published_at(4i)"=>"21", "published_at(5i)"=>"20", "custom_url"=>"", "source_url_title"=>"", "source_url"=>"", "user_id"=>"56", "browser_title"=>"", "meta_description"=>""}, "continue_editing"=>"false", "locale"=>:en}
Run Code Online (Sandbox Code Playgroud)

如果出现错误,您可能会发现这些也很有用:

app.cookies.to_hash
app.flash.to_hash
app.response # long, raw, HTML
Run Code Online (Sandbox Code Playgroud)

  • `NameError:未定义的局部变量或main:Object`的方法app (2认同)

Jyo*_*thu 11

您可以在Rails控制台中访问您的方法,如下所示

controller.method_name
helper.method_name
Run Code Online (Sandbox Code Playgroud)


Tba*_*abs 8

在rails 3中,试试这个:

session = ActionDispatch::Integration::Session.new(Rails.application)
session.get(url)
body = session.response.body
Run Code Online (Sandbox Code Playgroud)

正文将包含网址的HTML.

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


小智 7

之前的答案是调用助手,但以下内容将有助于调用控制器方法.我在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
Run Code Online (Sandbox Code Playgroud)

然后在rails控制台中你可以键入类似......

request(:controller => :show, :action => :show_frontpage)
Run Code Online (Sandbox Code Playgroud)

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


小智 5

对于控制器,您可以在 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
Run Code Online (Sandbox Code Playgroud)