如何从 Rails 控制台调用控制器/视图方法?
-
02-07-2019 - |
题
当我加载时 script/console
, ,有时我想使用控制器或视图辅助方法的输出。
有没有办法:
- 模拟请求?
- 根据所述请求从控制器实例调用方法?
- 测试辅助方法,通过所述控制器实例还是其他方式?
解决方案
要呼叫帮助者,请使用 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
其他提示
从脚本/控制台调用控制器操作并查看/操作响应对象的简单方法是:
> 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::集成::会话
这对我使用 Rails 2.1 和 2.3 有效,我没有尝试过早期版本。
如果需要从控制台进行测试(在 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..."
应用程序控制器方法:
foo = ActionController::Base::ApplicationController.new
foo.public_methods(true||false).sort
foo.some_method
路线助手:
app.myresource_path # => "/myresource"
app.myresource_url # => "http://www.example.com/myresource"
查看助手:
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\" />"
使成为:
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'
主动支持方法:
require 'active_support/all'
1.week.ago
=> 2013-08-31 10:07:26 -0300
a = {'a'=>123}
a.symbolize_keys
=> {:a=>123}
库模块:
> require 'my_utils'
=> true
> include MyUtils
=> Object
> MyUtils.say "hi"
evaluate: hi
=> true
这是通过控制台执行此操作的一种方法:
>> 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 调试器。有一个关于调试的 Rails 指南: http://guides.rubyonrails.org/debugging_rails_applications.html
基本上,使用 -u 选项启动服务器:
./script/server -u
然后在您想要访问控制器/帮助程序/等的脚本中插入一个断点。
class EventsController < ApplicationController
def index
debugger
end
end
当您发出请求并点击代码中的该部分时,服务器控制台将返回一个提示,您可以在其中发出请求、查看对象等。从命令提示符。完成后,只需输入“cont”即可继续执行。还有用于扩展调试的选项,但这至少应该让您开始。
如果方法是 POST
那么方法
app.post 'controller/action?parameter1=value1¶meter2=value2'
[这里的参数将根据您的适用情况]
否则如果是 GET
那么方法
app.get 'controller/action'
以下是如何发出经过身份验证的 POST 请求,以 Refinery 为例:
# 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}
如果出现错误,您可能会发现这些也很有用:
app.cookies.to_hash
app.flash.to_hash
app.response # long, raw, HTML
您可以在 Rails Console 中访问您的方法,如下所示
controller.method_name
helper.method_name
在 Rails 3 中,试试这个:
session = ActionDispatch::Integration::Session.new(Rails.application)
session.get(url)
body = session.response.body
正文将包含 url 的 HTML。
早期的答案是调用帮助程序,但以下内容将有助于调用控制器方法。我在 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
然后在 Rails 控制台中你可以输入类似...
request(:controller => :show, :action => :show_frontpage)
...html 将转储到控制台。
在任何控制器操作或视图内,您可以通过调用 安慰 方法。
例如,在控制器中:
class PostsController < ApplicationController
def new
console
@post = Post.new
end
end
或者在视图中:
<% console %>
<h2>New Post</h2>
这将在您的视图中呈现一个控制台。你不需要关心控制台调用的位置;它不会在调用时呈现,而是在您的 HTML 内容旁边呈现。
看: http://guides.rubyonrails.org/debugging_rails_applications.html
在 Rails 控制台中测试 Helper 方法的一种可能方法是
Struct.new(:t).extend(YourHelper).your_method(*arg)
并重新加载并执行
reload!; Struct.new(:t).extend(YourHelper).your_method(*arg)
对于控制器,您可以在 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
如果您添加了自己的帮助程序并且希望它的方法在控制台中可用,请执行以下操作:
- 在控制台执行
include YourHelperName
- 您的辅助方法现在可以在控制台中使用,使用它们调用
method_name(args)
在控制台中。
例子:假设你有 MyHelper (有一个方法 my_method
)在 'app/helpers/my_helper.rb` 中,然后在控制台中执行以下操作:
include MyHelper
my_helper.my_method