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 :: 통합 :: 세션
이것은 레일 2.1과 2.3을 사용하는 데 효과적입니다. 이전 버전을 시도하지 않았습니다.
콘솔에서 테스트 해야하는 경우 (레일 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..."
ApplicationController 메소드 :
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'
ActiveSupport 방법 :
require 'active_support/all'
1.week.ago
=> 2013-08-31 10:07:26 -0300
a = {'a'=>123}
a.symbolize_keys
=> {:a=>123}
LIB 모듈 :
> 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'
정유소를 사용하여 인증 된 사후 요청을 만드는 방법은 다음과 같습니다.
# 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
다음과 같이 레일 콘솔에서 메소드에 액세스 할 수 있습니다.
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 Console에서 다음과 같은 것을 입력 할 수 있습니다.
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
레일 콘솔에서 도우미 방법 테스트를위한 가능한 aproach는
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